package com.team5.aLife.Client;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.gson.Gson;

public class NotificationPowerActivity extends Activity {
	
	private String TAG = "NotificationPowerActivity:  ";
	
	private final String DELIMITER = "&";
	
	TextView deviceName;
	
	Spinner timeOne, timeTwo;
	
	Button submit;
	
	ALifeNotificationSetup notification;
	
	Context context = getBaseContext();
	
	private Gson gson = new Gson();
    private final String delimiter = "[&]+";
	
	private ProgressDialog m_ProgressDialog = null; 	// progress dialog
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.notification_power_switch);
        
        deviceName = (TextView) findViewById(R.id.NotificationPowerDeviceName);
        
        timeOne = (Spinner) findViewById(R.id.NotificationPowerTimeOne);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.notificatoin_power_time_array, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        timeOne.setAdapter(adapter);
        
        timeTwo = (Spinner) findViewById(R.id.NotificationPowerTimeTwo);
        ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(
                this, R.array.notificatoin_power_time_array2, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        timeTwo.setAdapter(adapter2);
        
        submit = (Button) findViewById(R.id.NotificationPowerSubmit);
        
        
    }
    
    public void onStart()
    {
    	super.onStart();
    	
    	submit.setOnClickListener(submitListener);
    	
    	deviceName.setText(DeviceListActivity.selectedDevice.getDeviceName());
    	
    	
    }
    
    private View.OnClickListener submitListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
        	
        	m_ProgressDialog = ProgressDialog.show(NotificationPowerActivity.this,    
                    "Please wait...", "Retrieving data ...", true);
        	
        	int firstTime = timeOne.getSelectedItemPosition();
        	int secondTime = timeTwo.getSelectedItemPosition();
        	
        	String triggeringCondition;
    		
    		triggeringCondition = firstTime + DELIMITER + secondTime;
        	
    		Log.i(TAG+"onClick", "The valueof triggeringCondition is:  " + triggeringCondition);
    		
        	if (isNotificationAlreadySetup())
        	{
        		notification.setTriggeringCondition(triggeringCondition);
        		
        		String replyString = socketDispatch.instance().sendReceive(new UpdateNotificationRequest(notification));
        		
        		String tokens[] = replyString.split(delimiter);
        		
        		TransactionReply updateNotificationReply = (TransactionReply) gson.fromJson(tokens[1], TransactionReply.class);
        		
        		displayNotificationChangeResult(updateNotificationReply.wasTransactionSuccessful());
        		
        	}
        	else
        	{ 
        		notification = new ALifeNotificationSetup(DeviceListActivity.selectedDevice.getDeviceID(),  
        												  LoginActivity.activeUser.getUserID(), 
        												  DeviceListActivity.selectedDevice.getDeviceType(), 
        												  triggeringCondition);
        		
        		Log.i(TAG+"onClick", "The notification properties: " +
    				  DeviceListActivity.selectedDevice.getDeviceID() + " " +
					  LoginActivity.activeUser.getUserID() + " " +
					  DeviceListActivity.selectedDevice.getDeviceType() + " " +
					  triggeringCondition);
        		
        		String replyString = socketDispatch.instance().sendReceive(new InsertNotificationRequest(notification));
        		
        		String tokens[] = replyString.split(delimiter);
        		
        		TransactionReply insertNotificationReply = (TransactionReply) gson.fromJson(tokens[1], TransactionReply.class);
        		
        		displayNotificationChangeResult(insertNotificationReply.wasTransactionSuccessful());
        		
        	}
        	
        	m_ProgressDialog.dismiss();
        	
        	socketDispatch.instance().sendReceive(new BackgroundServicesOnStartRequest());
        	finish();
            
        }
    };
    
    public void displayNotificationChangeResult(boolean result)
    {
    	Log.i(TAG+"displayNotificationChangeResult", "I am in displayNotificationChangeResult.  My result was: " + result);
    	
    	if (result)
        {
        	AlertDialog.Builder builder = new AlertDialog.Builder(NotificationPowerActivity.this);
        	builder.setMessage("Transaction Successful")
        	       .setCancelable(false)
        	       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
        	           public void onClick(DialogInterface dialog, int id) {
        	        	   //RegisterDeviceActivity.this.finish();
        	           }
        	       });
        	AlertDialog alert = builder.create();
        	alert.show();
        }
        else
        {
        	AlertDialog.Builder builder = new AlertDialog.Builder(NotificationPowerActivity.this);
        	builder.setMessage("Transaction Failed")
        	       .setCancelable(false)
        	       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
        	           public void onClick(DialogInterface dialog, int id) {
        	        	   //RegisterDeviceActivity.this.finish();
        	           }
        	       });
        	AlertDialog alert = builder.create();
        	alert.show();
        }
    }
    
    private boolean isNotificationAlreadySetup()
    {
    	
    	String replyString = socketDispatch.instance().sendReceive(new GetUsersNotificationRequest(DeviceListActivity.selectedDevice, 
    															   LoginActivity.activeUser ));
    	
    	Log.i(TAG+"isNotificationAlreadySetup", replyString);
    	
    	String tokens[] = replyString.split(delimiter);
    	              
    	GetUserNotificiationReply reply = (GetUserNotificiationReply) gson.fromJson(tokens[1], GetUserNotificiationReply.class); 
    	
    	notification = reply.getNotification();
    	
    	return reply.wasTransactionSuccessful();
    		
    }

}
