package nl.powercraft.tagtracker;


import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.net.Uri;
import android.nfc.NfcAdapter;
import android.nfc.tech.NfcA;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.ToggleButton;

public class TagTrackerActivity extends Activity {
	private NfcAdapter mAdapter;
    private PendingIntent mPendingIntent;
    private IntentFilter[] mFilters;
    private String[][] mTechLists;
    private FileHandler fh = new FileHandler();
    private boolean writeAllow = false;
    private ArrayList<String> cardID = new ArrayList<String>();
    private RelativeLayout mScreen;
    
    @SuppressWarnings("unchecked")
	@Override
    public void onCreate(Bundle savedState) {
        super.onCreate(savedState);
        final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        WakeLock mWakeLock;
        setContentView(R.layout.main);
        final Button button = (Button) findViewById(R.id.zend);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	zenden();
            }
        });
        SharedPreferences p = getPreferences(MODE_PRIVATE);
        writeAllow = p.getBoolean("writeAllow", false);
        cardID = (ArrayList<String>) ObjectSerializer.deserialize(p.getString("cardID", ObjectSerializer.serialize(new ArrayList<String>())));
        ToggleButton tg = (ToggleButton) findViewById(R.id.status);
        tg.setChecked(writeAllow);
        mScreen = (RelativeLayout) findViewById(R.id.Screen);
        mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE,"");    
        mWakeLock.acquire();
        mAdapter = NfcAdapter.getDefaultAdapter(this);

        // Create a generic PendingIntent that will be deliver to this activity. The NFC stack
        // will fill in the intent with the details of the discovered tag before delivering to
        // this activity.
        mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

        // Setup an intent filter for all MIME based dispatches
        IntentFilter tech = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
        try {
            tech.addDataType("*/*");
        } catch (MalformedMimeTypeException e) {
            throw new RuntimeException("fail", e);
        }
        mFilters = new IntentFilter[] {
               tech,
        };

        // Setup a tech list for all NfcF tags
        mTechLists = new String[][] { new String[] { NfcA.class.getName() } };
    }
    
    public void onToggleClicked(View v) {
        // Perform action on clicks
        if (((ToggleButton) v).isChecked()) {
        	if(fh.init())
            {
            	fh.writeStart(DateFormat.getDateTimeInstance().format(new Date()));
            	writeAllow = true;
            }
            else
            {
            	finish();
            }
        } else {
            fh.writeEnd(DateFormat.getDateTimeInstance().format(new Date()));
            writeAllow = false;
            cardID.clear();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mAdapter != null) mAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters,
                mTechLists);
    }

    @Override
    public void onNewIntent(Intent intent) {
    	if(writeAllow)
    	{
	    	byte[] bid = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID); 
		    	try
		    	{
		    		String uid = getHexString(bid);
		    		String time = DateFormat.getDateTimeInstance().format(new Date());
		    		if(!cardID.contains(uid))
			    	{
			    		//Log.i("Foreground dispatch", "Discovered tag with ID: " + uid);
			            //mText.append("\r\n["+time+"] Discovered tag " + ++mCount + " with ID: " + uid);
			            fh.writeUID(uid, time);
			            cardID.add(uid);
			            setBackground(0xFF00FF00, 200);
			            playSound(this.getApplicationContext(), false);
			    	}
			    	else
			    	{
			    		setBackground(0xFFFFEE00, 1000);
			    		playSound(this.getApplicationContext(), true);
			    		//mText.append("\r\n["+time+"] Tag ID " + uid + " is already added.");
			    	}
		    	}
		    	catch (Exception e)
		    	{
		    		Log.e("TagTracker", "" + e);
		    	}
    	}
    }
    
    public void playSound(Context context, boolean twice) throws IllegalArgumentException, SecurityException, IllegalStateException, IOException {
		final ToneGenerator tg = new ToneGenerator(AudioManager.STREAM_ALARM, 100);
	    if(!twice)
	    {
	    	tg.startTone(ToneGenerator.TONE_PROP_BEEP);
	    }	
	    else
		{
			//tg.startTone(ToneGenerator.TONE_PROP_BEEP);
			tg.startTone(ToneGenerator.TONE_PROP_ACK);
		}
		
    }
        
    public static String getHexString(byte[] b) throws Exception {
    	  String result = "";
    	  for (int i=0; i < b.length; i++) {
    	    result +=
    	          Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
    	  }
    	  return result;
    	}
    
    public void setBackground(int color, int time)
    {
    	mScreen.setBackgroundColor(color);
    	Handler handler = new Handler(); 
        handler.postDelayed(new Runnable() { 
             public void run() { 
            	mScreen.setBackgroundColor(android.R.color.white); 
             } 
        }, time);     	
    }
    @Override
    public void onPause() {
        super.onPause();
        SharedPreferences preferences = getPreferences(MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean("writeAllow", writeAllow); // value to store
        editor.putString("cardID", ObjectSerializer.serialize(cardID));
        editor.commit();
        if (mAdapter != null) mAdapter.disableForegroundDispatch(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.lo_menu, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.add_uid:
                addUID();
                return true;
            case R.id.add_note:
                addNote();
                return true;
            case R.id.stopsend:
            	stopSend();
            	return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
    public void addUID()
    {
    	if(writeAllow)
    	{
	    	AlertDialog.Builder alert = new AlertDialog.Builder(this);                 
	    	alert.setTitle("UID Toevoegen");  
	
	    	// Set an EditText view to get user input   
	    	final EditText input = new EditText(this); 
	    	alert.setView(input);

    	    alert.setPositiveButton("Toevoegen", new DialogInterface.OnClickListener() {  
    	    public void onClick(DialogInterface dialog, int whichButton) {  
    	        String value = input.getText().toString();
    	        fh.writeUID(value, DateFormat.getDateTimeInstance().format(new Date()));
    	        return;                  
    	       }  
    	     });  

    	    alert.setNegativeButton("Annuleren", new DialogInterface.OnClickListener() {

    	        public void onClick(DialogInterface dialog, int which) {
    	            // TODO Auto-generated method stub
    	            return;   
    	        }
    	    });
    	    alert.show();
    	}
    	else
    	{
    		AlertDialog.Builder alert = new AlertDialog.Builder(this, 4);                 
	    	alert.setTitle("Oeps!"); 
	    	alert.setMessage("Druk op start om een UID toe te voegen");
	    	alert.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					return;
				}
			});
	    	alert.show();
    	}
    }
    
    public void addNote()
    {
    	if(writeAllow)
    	{
	    	AlertDialog.Builder alert = new AlertDialog.Builder(this);                 
	    	alert.setTitle("Notitie Toevoegen");  
	
	    	// Set an EditText view to get user input   
	    	final EditText input = new EditText(this); 
	    	alert.setView(input);

    	    alert.setPositiveButton("Toevoegen", new DialogInterface.OnClickListener() {  
    	    public void onClick(DialogInterface dialog, int whichButton) {  
    	        String value = input.getText().toString();
    	        fh.writeNote(value);
    	        return;                  
    	       }  
    	     });  

    	    alert.setNegativeButton("Annuleren", new DialogInterface.OnClickListener() {

    	        public void onClick(DialogInterface dialog, int which) {
    	            // TODO Auto-generated method stub
    	            return;   
    	        }
    	    });
    	    alert.show();
    	}
    	else
    	{
    		AlertDialog.Builder alert = new AlertDialog.Builder(this, 4);                 
	    	alert.setTitle("Oeps!"); 
	    	alert.setMessage("Druk op start om een Notitie toe te voegen");
	    	alert.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					return;
				}
			});
	    	alert.show();
    	}
    }
    public void stopSend()
    {
    	writeAllow = false;
    	ToggleButton tg = (ToggleButton) findViewById(R.id.status);
        tg.setChecked(writeAllow);
    	AlertDialog.Builder alert = new AlertDialog.Builder(this);                 
    	alert.setTitle("Email Zenden");  

    	// Set an EditText view to get user input   
    	final EditText input = new EditText(this); 
    	input.setHint("Email");
    	input.setInputType(32);
    	alert.setView(input);

	    alert.setPositiveButton("Verder", new DialogInterface.OnClickListener() {  
	    public void onClick(DialogInterface dialog, int whichButton) {  
	        String value = input.getText().toString();
	        Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND); 
	        emailIntent.setType("text/xml");
	        emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] 
	        {value}); 
	        emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, 
	        "Tag Track from " + DateFormat.getDateTimeInstance().format(new Date())); 
	        emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, 
	        "XML Attached"); 
	        File root = new File(Environment.getExternalStorageDirectory(), "TagTracker");
		    File xmlfile = new File(root, "tags.xml");
	        emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://"+ xmlfile));
	        startActivity(Intent.createChooser(emailIntent, "Stuur Email"));
	        return;                  
	       }  
	     });  
	    alert.show();
    }
    public void zenden()
    {
    	if(!writeAllow)
    	{
    		AlertDialog.Builder alert = new AlertDialog.Builder(this);                 
        	alert.setTitle("Email Zenden");  

        	// Set an EditText view to get user input   
        	final EditText input = new EditText(this); 
        	input.setHint("Email");
        	input.setInputType(32);
        	alert.setView(input);

    	    alert.setPositiveButton("Verder", new DialogInterface.OnClickListener() {  
    	    public void onClick(DialogInterface dialog, int whichButton) {  
    	        String value = input.getText().toString();
    	        Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND); 
    	        emailIntent.setType("text/xml");
    	        emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] 
    	        {value}); 
    	        emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, 
    	        "Tag Track from " + DateFormat.getDateTimeInstance().format(new Date())); 
    	        emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, 
    	        "XML Attached"); 
    	        File root = new File(Environment.getExternalStorageDirectory(), "TagTracker");
    		    File xmlfile = new File(root, "tags.xml");
    	        emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://"+ xmlfile));
    	        startActivity(Intent.createChooser(emailIntent, "Stuur Email"));
    	        return;                  
    	       }  
    	     });  
    	    alert.show();
    	}
    	else
    	{
    		AlertDialog.Builder alert = new AlertDialog.Builder(this, 4);                 
	    	alert.setTitle("Oeps!"); 
	    	alert.setMessage("Druk op stop om te verzenden");
	    	alert.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					return;
				}
			});
	    	alert.show();
    	}
    }
}