package com.phoceis.STdatalogger;
import com.phoceis.STdatalogger.R;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.NfcV;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;


public class changeSettingsActivity extends Activity implements SeekBar.OnSeekBarChangeListener	{
	
	private Button saveSettings;
	private ToggleButton togglebutton;
	public SeekBar sliderDelay;
	public TextView delay;
	public byte OldbyteDelay = (byte)0xFF;
	public byte byteOverwrite = (byte)0xFF;
	public byte[] ConfigArray;
	private final int POLLING = 400;
	private boolean isConnected = true;
	
	private NfcAdapter mAdapter;
	private PendingIntent mPendingIntent;
	private IntentFilter[] mFilters;
	private String[][] mTechLists;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        
		super.onCreate(savedInstanceState);
        setContentView(R.layout.changesettings);
        
        saveSettings = (Button) this.findViewById(R.id.saveSettings);
        sliderDelay = (SeekBar) this.findViewById(R.id.sliderDelay);
        sliderDelay.setOnSeekBarChangeListener(this);
        delay = (TextView) this.findViewById(R.id.delay);
        togglebutton = (ToggleButton) this.findViewById(R.id.togglebutton);
        
        mAdapter = NfcAdapter.getDefaultAdapter(this);
        mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
        mFilters = new IntentFilter[] {
                ndef,
        };
        mTechLists = new String[][] { new String[] { android.nfc.tech.NfcV.class.getName() } };         
        
        myApplication ma = (myApplication)getApplication();
        ConfigArray = ma.getConfiguration();
        OldbyteDelay = ma.getCurrentDelay();
        
		if(ma.getCurrentOverwrite() ==0x11)
		{
			togglebutton.setChecked(true);
		}
		else
		{
			togglebutton.setChecked(false);
		}
		
		if (ma.getCurrentDelay() == 0x0D)
		{
			delay.setText("1 s");
			sliderDelay.setProgress(10);
		}
		else if (ma.getCurrentDelay() == 0x0E)
		{
			delay.setText("2 s");
			sliderDelay.setProgress(40);
		}
		else if (ma.getCurrentDelay() == 0x0F)
		{
			delay.setText("12 s");
			sliderDelay.setProgress(60);
		}
		else if (ma.getCurrentDelay() == 0x10)
		{
			delay.setText("30 second");
			sliderDelay.setProgress(95);
		}
		else
		{
			delay.setText("delay not supported");
		}

		
		/* *********************** BUTTON WRITE SETTINGS TO DATALOGGER ***************************** */
        this.saveSettings.setOnClickListener(new View.OnClickListener() {			
    		@Override
			public void onClick(View v) 
    		{		
				byte[] WriteSingleBlockCommand = new byte[]{ (byte) 0x0A,  (byte) 0x21,  (byte) 0x00,  (byte) 0x00,  (byte) 0x55,  ConfigArray[2],   ConfigArray[3],  ConfigArray[4] };
				
				myApplication ma = (myApplication)getApplication();
				NfcV nfcvTag = NfcV.get(ma.getCurrentTag());
				if(nfcvTag.isConnected())
				{
					isConnected = true;
				}
				else
				{
					isConnected = false;
				}
				
				
				for(int i =0; i<POLLING;i++)
				{
					try 
					{
						if(!isConnected)
							nfcvTag.connect();
						byte[] response = nfcvTag.transceive(WriteSingleBlockCommand);				
						nfcvTag.close();
						isConnected = false;
						if(response[0] == 0x00)
						{
		    				if(ConfigArray[3] != OldbyteDelay && ConfigArray[1] == 44)
		    				{
		    					Toast.makeText(getApplicationContext(), "SUCCESS : new settings saved & DATALOGGER STARTED", 500).show();
		    				}
		    				else
		    					Toast.makeText(getApplicationContext(), "SUCCESS : new settings saved", 500).show();
		    				ma.setConfiguration(ConfigArray);
		    				ma.setCurrentOverwrite(ConfigArray[2]);
		    				ma.setCurrentDelay(ConfigArray[3]);
		    				i=POLLING;
		    				finish();
						}
					}
					catch(Exception e)
					{
						isConnected = true;
						if(i==POLLING-1)
	    				{
							Toast.makeText(getApplicationContext(), "ERROR : you must place the phone close to the datalogger in order to save new settings", 1000).show();
	    				}
					}
				}
    		}	
    	});
        
       
        /* *********************** BUTTON ON/OFF OVERWRITE ***************************** */
        this.togglebutton.setOnClickListener(new View.OnClickListener() {			
    		@Override
			public void onClick(View v) 
    		{	
    			if(togglebutton.isChecked())
    			{
					//Authorize Overwrite
    				ConfigArray[2] = 0x11;
    			}
    			else
    			{
					ConfigArray[2] = 0x00;
    			}
    		}	
    	});        
	}
	
	/* *********************** SLIDER BAR ACQUISITION FREQUENCY ***************************** */
	public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
		delay.setText(Integer.toString(progress));
		if(progress >= 0 && progress < 30)
		{
			delay.setText("1s");
			ConfigArray[3]=(byte)0x0D;
		}
		
		else if(progress >= 30 && progress < 50)
		{
			delay.setText("2s");
			ConfigArray[3]=(byte)0x0E;
		}
			
		else if(progress >= 50 && progress < 70)
		{
			delay.setText("12s");
			ConfigArray[3]=(byte)0x0F;
		}
			
		else if(progress >= 70 && progress <= 100)
		{
			delay.setText("30s");
			ConfigArray[3]=(byte)0x10;
		}		
    }
	
	public void onStartTrackingTouch(SeekBar seekBar) {
		// MANDATORY
    }

    public void onStopTrackingTouch(SeekBar seekBar) {
		//MANDATORY
    }
    
    @Override
    public void onResume() {
    	//saveSettings.setEnabled(true);
        super.onResume();
        mAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters, mTechLists);
    }
    
    @Override
    public void onNewIntent(Intent intent) {
       Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);     
       myApplication ma = (myApplication)getApplication();
       ma.setCurrentTag(tagFromIntent);
       
    }
    
}
