package com.tumbleweed.riseshine;

import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Calendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

//this class will act as a helper class
//it performs scanning of codes and handles the outcome.

//it also loads and saves certain information to files.

//the next number in the morning routine sequence is stored
//if the program is in strict mode or not is stored
//when the alarm is supposed to go off is stored (that value is stored as 0 if no alarm is set)
//and the playlist that is selected for automatic playback when last alarm is scanned, is stored.

public class RiseShineHelper 
{

	public void init(Activity act)
	{
		offTag = false;
		loadSeqNum(act);
		loadSettings(act);
		
		
	}
	 public void loadSeqNum(Activity act)
    {
   	 try
		 {
			 InputStream inp = act.openFileInput("seqfile.txt");

			 BufferedInputStream bis = null;
			 DataInputStream dis = null;

			 bis = new BufferedInputStream(inp);
			 dis = new DataInputStream(bis);

			 String line = dis.readLine();
			 seqNumExpected = Integer.decode(line);
				
			 
		 }
		 catch(IOException io)
		 {
			 io.printStackTrace();
		 }
		 
		 
   }
	 
	public void savePlayListToFile(String playlistID,Activity act)
	{
		try
    	{
    		OutputStream out = act.openFileOutput("playlistid.txt", Context.MODE_PRIVATE);

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

    		buffwr.write((playlistID) + "\n");
    		buffwr.close();


    	}
    	catch(IOException io)
    	{
    		io.printStackTrace();
    	}
	}
	
	public String loadPlayListFromFile(Activity act)
	{
		//-2 is the default playlist, which is "play all"
		String res = "-2";
		try
		 {
			 InputStream inp = act.openFileInput("playlistid.txt");

			 BufferedInputStream bis = null;
			 DataInputStream dis = null;

			 bis = new BufferedInputStream(inp);
			 dis = new DataInputStream(bis);

			 res = dis.readLine();	
			 
		 }
		 catch(IOException io)
		 {
			 io.printStackTrace();
		 }
	
		 return res;
		 
	}
	
	 void updateSeqNum(Activity act)
    {
    	try
    	{
    		OutputStream out = act.openFileOutput("seqfile.txt", Context.MODE_PRIVATE);

    		OutputStreamWriter osw = new OutputStreamWriter(out);
    		BufferedWriter buffwr = null;
    		buffwr = new BufferedWriter(osw);
    		seqNumExpected++;
    		buffwr.write((seqNumExpected) + "\n");
    		buffwr.close();


    	}
    	catch(IOException io)
    	{
    		io.printStackTrace();
    	}
    }
	
	 boolean offTag;
	 
	 
	 public void codeScanned(Activity act, String data,boolean inAlarmMode)
	{
		 boolean hasNothingToHandle = false;
		 
		 offTag = parseIfOffTag(data);
		 
		 lastSeq = parseLastSeq(data);
		 
		 scannedWrongSeq = false;
		 
		 if(!lastSeq && !offTag)
		 {
			 seqNumScanned = parseSeqNum(data);
			 if(seqNumScanned!=seqNumExpected)
			 {
				 //someone is trying to scan in the wrong bar code.

				 scannedWrongSeq = true;
				 hasNothingToHandle = false;
			 }
			 else
			 {
				 int hours = parseHours(data);
				 int minutes = parseMinutes(data);

				  
				 //we shall turn on a new alarm.


				 //update seq number to new value and save to sequence file. 
				 updateSeqNum(act);

				 // want alarm to go of at. now + hours and minutes
				 Calendar alarmTime = Calendar.getInstance();
				 
				 loadAlarmTimeFromDisk(act);
			
				 long bonusTime = 0;
				 if(!inAlarmMode)
				 {
					 //alarmTime is currently NOWTIME.
					
					 bonusTime += alarmSupposedToGoOffMs - alarmTime.getTimeInMillis();
					 
				 }
				
				 
				 alarmTime.add(Calendar.HOUR, hours);
				 alarmTime.add(Calendar.MINUTE, minutes);

				 
				 issueAlarm(alarmTime.getTimeInMillis() + bonusTime,act);
				 hasNothingToHandle = true;
			 }
		 }
		 else
		 {
			 lastSeq = true;
			 saveAlarmTimeToDisk(act,0);
		 }
		 
	}
	 
	 boolean parseLastSeq(String txt)
	    {
	    	return txt.equalsIgnoreCase("LAST");
	    }
	 
	 boolean parseIfOffTag(String txt)
	    {
	    	return txt.equalsIgnoreCase("OFF");
	    }
	    
	    int parseSeqNum(String txt)
	    {
	    	int spot = txt.indexOf(':');
	    	return Integer.decode(txt.substring(0, spot));
	    }
	    
	    int parseHours(String txt)
	    {
	    	int spot = txt.indexOf(':');
	    	String subtxt = txt.substring(spot+1, txt.length());
	    	int spot2 = subtxt.indexOf(':');
	    	return Integer.decode(subtxt.substring(0,spot2));
	    }
	    
	    int parseMinutes(String txt)
	    {
	    	int spot = txt.indexOf(':');
	    	String subtxt = txt.substring(spot+1, txt.length());
	    	int spot2 = subtxt.indexOf(':');
	    	return Integer.decode(subtxt.substring(spot2+1));
	    }
	    
	    void saveAlarmTimeToDisk(Activity act,long alarmAtTimeMs)
	    {
	    	alarmSupposedToGoOffMs = alarmAtTimeMs;
	    	try
	    	{
	    		
	    		OutputStream out = act.openFileOutput("alarmtime.txt", Context.MODE_PRIVATE);

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

	    		buffwr.write(alarmAtTimeMs + "\n");
	    		buffwr.close();
	    		

	    	}
	    	catch(IOException io)
	    	{
	    		io.printStackTrace();
	    	}
	    	
	    	
	    	
	    	 
	    }
	    
	    void loadAlarmTimeFromDisk(Activity act)
	    {
	    	
 
	    	 try
			 {
				 InputStream inp = act.openFileInput("alarmtime.txt");

				 BufferedInputStream bis = null;
				 DataInputStream dis = null;

				 bis = new BufferedInputStream(inp);
				 dis = new DataInputStream(bis);
	 
				 alarmSupposedToGoOffMs = Long.decode(dis.readLine());
				 
			 }
			 catch(IOException io)
			 {
				 io.printStackTrace();
				 alarmSupposedToGoOffMs = 0;
			 }
		
	    }
	    
	    
	    private static String pad(int c) {
        	if (c >= 10)
        		return String.valueOf(c);
        	else
        		return "0" + String.valueOf(c);
        }
	    
	   public void updateAlarmInfoText(TextView tv)
	   {
		   Calendar alarmToOffAtTime = Calendar.getInstance();
		   alarmToOffAtTime.setTimeInMillis(alarmSupposedToGoOffMs);
		   
		   Calendar nowTime = Calendar.getInstance();
		   
		   if(alarmToOffAtTime.before(nowTime))
		   {
			   tv.setText("no alarm set");
			   return;
		   }
		   
		   int hour = alarmToOffAtTime.get(Calendar.HOUR_OF_DAY);
		   int min = alarmToOffAtTime.get(Calendar.MINUTE);
		   
		   StringBuilder time = new StringBuilder().append(pad(hour)).append(":").append(pad(min));
		   
		   String str =seqNumExpected +  ". alarm post goes of at " + time; 
		   tv.setText(str);
	   }
	   
	   public boolean isAlarmSet(Activity act)
	   {
		   //indications of alarm not being set is alarmSupposedToGoOffMs being 0
		   loadAlarmTimeFromDisk(act);
		   return alarmSupposedToGoOffMs!=0;
	   }
	   
	   public void onAlarmCancelOrExit(Activity act)
	   {
		   //this makes the alarm time that is saved to disk become waay in the past.
		   saveAlarmTimeToDisk(act,0);
	   }
	    
	    public void issueAlarm(long triggerTime,Activity act)
	    {
	    	saveAlarmTimeToDisk(act,triggerTime);
	    	Intent intent2 = new Intent(act, RiseShineAlarm.class);
			PendingIntent sender = PendingIntent.getBroadcast(act,
					0, intent2, 0);
			
			// Schedule the alarm!
			AlarmManager am = (AlarmManager)act.getSystemService(Activity.ALARM_SERVICE);
			am.set(AlarmManager.RTC_WAKEUP, triggerTime, sender);
	    }
	    
	    public void administerDigitalChocolate(Activity act)
	    {
	    	if(offTag)
	    		return;
            Intent snackIntent = new Intent(act,DigitalChocolate.class);
			snackIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			act.startActivity(snackIntent);
	    }
	    
	    void loadSettings(Activity act)
	    {
	    	 try
			 {
				 InputStream inp = act.openFileInput("settings.txt");

				 BufferedInputStream bis = null;
				 DataInputStream dis = null;

				 bis = new BufferedInputStream(inp);
				 dis = new DataInputStream(bis);

				 String line = dis.readLine();
				 if(line.equals("strict"))
					 strictMode = true;
				 else
					 strictMode = false;
					
				 
			 }
			 catch(IOException io)
			 {
				 io.printStackTrace();
			 }
			 
			 
	    }
	
	 int seqNumExpected;
	 boolean strictMode;
	 
	 public boolean isInStrictMode()
	 {
		 return strictMode;
	 }

	 public boolean getIfScannedWrongSeq()
	 {
		 return scannedWrongSeq;
	 }
	 
	 public boolean getIfLastSeqScanned()
	 {
		 return lastSeq;
	 }
	 
	 boolean scannedWrongSeq;
	 boolean lastSeq;
	 int seqNumScanned;
	 
	 
	 long alarmSupposedToGoOffMs;
	 
}
