package com.tumbleweed.riseshine;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Calendar;
import java.util.Date;


import android.app.Activity;
import android.app.AlarmManager;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.TimePicker;

public class RiseShine extends Activity 
{
   
	Button selPlaylistButton;
	Button cancelAllButton;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        rsHelper = new RiseShineHelper();
        rsHelper.init(this);
        
        text = (TextView) findViewById(R.id.TextView1);
        mTimeDisplay = (TextView) findViewById(R.id.TextView01);
        mPickTime = (Button) findViewById(R.id.Button02);

        mScanCode = (Button) findViewById(R.id.Button01);
        mStrictMode = (CheckBox) findViewById(R.id.CheckBox01);
        selPlaylistButton = (Button) findViewById(R.id.Button03);
        cancelAllButton = (Button) findViewById(R.id.Button04);
        
        selPlaylistButton.setOnClickListener(new View.OnClickListener() 
        {
             public void onClick(View v) 
             {
            	
            	 Intent intentStart = new Intent(Intent.ACTION_CREATE_SHORTCUT);
            	 intentStart.setComponent(new ComponentName("com.android.music","com.android.music.PlaylistShortcutActivity"));
                 startActivityForResult(intentStart,1);
             }
        }
        );
        
        cancelAllButton.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v) 
            {
            	//stop all alarm systems.
				Intent intent2 = new Intent(RiseShine.this, RiseShineAlarm.class);
                PendingIntent sender = PendingIntent.getBroadcast(RiseShine.this,
                        0, intent2, 0);
                sender.cancel();

                
                rsHelper.onAlarmCancelOrExit(RiseShine.this);
                
                finish();
            }
       }
       );
        
        // add a click listener to the button
        mPickTime.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v) 
            {
                showDialog(TIME_DIALOG_ID);
            }
        });
        
        mStrictMode.setOnClickListener(new View.OnClickListener()
        {
        	public void onClick(View v)
        	{
        		saveState();
        	}
        	
        });
        
        mStrictMode.setChecked(rsHelper.isInStrictMode());

        if(!rsHelper.isAlarmSet(this))
        {
        	mScanCode.setText("alarm not set, scan disabled");
        	
        }
        else
        {
        	
        	mScanCode.setOnClickListener(new View.OnClickListener() 
        	{
        		public void onClick(View v) {
        			Intent intent = new Intent("com.google.zxing.client.android.SCAN");
        			intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
        			startActivityForResult(intent, 0);
        			 
        		}
        	});
        }
        
       
    }
        
        public void onActivityResult(int requestCode, int resultCode, Intent intent) 
        {
        	if (requestCode == 0) 
        	{
        		if (resultCode == RESULT_OK) 
        		{
        			String contents = intent.getStringExtra("SCAN_RESULT");
        			String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
        			// Handle successful scan

        			rsHelper.codeScanned(this, contents,false);
        			
        			if(rsHelper.getIfLastSeqScanned())
        			{
        				//stop all alarm systems.
        				Intent intent2 = new Intent(RiseShine.this, RiseShineAlarm.class);
                        PendingIntent sender = PendingIntent.getBroadcast(RiseShine.this,
                                0, intent2, 0);
                        sender.cancel();
                        
                       rsHelper.onAlarmCancelOrExit(RiseShine.this);
                        
                       rsHelper.administerDigitalChocolate(this);
                        
                        
        			}
        			else
        			{
        				//we have scanned something in the sequence.
        				updateDisplay();
        			}
        			
        		} else if (resultCode == RESULT_CANCELED) {
        			// Handle cancel
        		}
        	}
        	else if ( requestCode == 1)
        	{
        		if (resultCode == RESULT_OK) 
         		{
         			Bundle bundy = intent.getExtras();
         			
         			Intent shortcut = (Intent) bundy.get(Intent.EXTRA_SHORTCUT_INTENT);
         			
         			 String playlistID = shortcut.getStringExtra("playlist");
         			 Log.d("playlist returned", playlistID);
         			 rsHelper.savePlayListToFile(playlistID, this);
         			 
         		}
        	}
        }
        
        @Override
        protected Dialog onCreateDialog(int id) 
        {
        	switch (id) {
        	case TIME_DIALOG_ID:
        		return new TimePickerDialog(this,
        				mTimeSetListener, mHour, mMinute, false);
        	}
        	return null;
        }

        // updates the time we display in the TextView
        private void updateDisplay() 
        {
        	rsHelper.updateAlarmInfoText(mTimeDisplay);
        	
        }

        // the callback received when the user "sets" the time in the dialog
        private TimePickerDialog.OnTimeSetListener mTimeSetListener =
        	new TimePickerDialog.OnTimeSetListener() {
        	public void onTimeSet(TimePicker view, int hourOfDay, int minute) 
        	{
        		mHour = hourOfDay;
        		mMinute = minute;
        	
        		  
                 // want alarm to go of at. set time.
                 Calendar alarmTime = Calendar.getInstance();
                 
                 alarmTime.set(Calendar.HOUR_OF_DAY, mHour);
                 alarmTime.set(Calendar.MINUTE, mMinute);
                 
                 Calendar now = Calendar.getInstance();
                 if(alarmTime.before(now))
                 {
                  //make date the future.
                	 alarmTime.add(Calendar.DATE, 1);
                	 
                 }
                
                 
                 rsHelper.issueAlarm(alarmTime.getTimeInMillis(), RiseShine.this);
                 	
            	
                 saveState();
                 saveSeqNum();
                 
                 //reload settings after saving them.
                 rsHelper.init(RiseShine.this);
               
                 updateDisplay();
               
                 //since we've set an alarm, enable scan button.
                 mScanCode.setText("scan");
                 mScanCode.setOnClickListener(new View.OnClickListener() 
             	{
             		public void onClick(View v) {
             			Intent intent = new Intent("com.google.zxing.client.android.SCAN");
             			intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
             			startActivityForResult(intent, 0);

             		}
             	});

        	}
        };


        void saveState()
        {
        	try
        	{
        		OutputStream out = openFileOutput("settings.txt", Context.MODE_PRIVATE);

        		OutputStreamWriter osw = new OutputStreamWriter(out);
        		BufferedWriter buffwr = null;
        		buffwr = new BufferedWriter(osw);


        		
        		if( mStrictMode.isChecked() )
        			buffwr.write("strict\n");
        		else
        			buffwr.write("nonstrict\n");

        		buffwr.close();


        	}
        	catch(IOException io)
        	{
        		io.printStackTrace();
        	}
        }
        
        void saveSeqNum()
        {
        	try
        	{
        		OutputStream out = openFileOutput("seqfile.txt", Context.MODE_PRIVATE);

        		OutputStreamWriter osw = new OutputStreamWriter(out);
        		BufferedWriter buffwr = null;
        		buffwr = new BufferedWriter(osw);

        		buffwr.write("1\n");
        		buffwr.close();


        	}
        	catch(IOException io)
        	{
        		io.printStackTrace();
        	}
        }
        
        
        private static String pad(int c) {
        	if (c >= 10)
        		return String.valueOf(c);
        	else
        		return "0" + String.valueOf(c);
        }

        @Override
        public void onResume() 
        {
        	super.onResume();
        	
        	 //reload
            rsHelper.init(RiseShine.this);
            
        	updateDisplay();
        	
        	if(!rsHelper.isAlarmSet(this))
            {
            	mScanCode.setText("alarm not set, scan disabled");
            	mScanCode.setOnClickListener(new View.OnClickListener() 
            	{
            		public void onClick(View v) 
            		{

            		}
            	});
            }
        }
        
        @Override
        public void onDestroy() 
        {
        	super.onDestroy();
        	
        }
        

        	RiseShineHelper rsHelper;
 
    private CheckBox mStrictMode;
    private Button mScanCode;
    private Button mPickTime;
    private TextView text;
    private TextView mTimeDisplay;
    private int mHour;
    private int mMinute;
    static final int TIME_DIALOG_ID = 0;


}