package com.androidbegin.buttonclicktutorial;

import java.util.ArrayList;
import java.util.Date;


import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.widget.Toast;

public class AlarmService extends IntentService 
{
	
	private static final String TAG = "AlarmService";
	
	public static final String POPULATE = "POPULATE";
	public static final String CREATE = "CREATE";
	public static final String CANCEL = "CANCEL";
	
	private IntentFilter matcher;
	
	long time; 
	long alarmId;
	String titre;
	

	DB_alarm db;
	private SQLiteDatabase dataBase;

	final static ArrayList<appointment> appointment_DB_boot = new ArrayList<appointment>();

	
	public AlarmService() 
	{
		super(TAG);
		matcher = new IntentFilter();
		matcher.addAction(POPULATE);
		matcher.addAction(CREATE);
		matcher.addAction(CANCEL);
	}

	@Override
	protected void onHandleIntent(Intent intent)
	{
			String action = intent.getAction();
			
			db = new DB_alarm(getApplicationContext());
			
			alarmId = intent.getLongExtra("ALARMID", -1);
			titre = intent.getStringExtra("TITRE");
			time = intent.getLongExtra("TIME", -1);
			
			//String alarmMsgId = intent.getStringExtra(AlarmMsg.COL_ID);
			//String startTime = intent.getStringExtra(Alarm.COL_FROMDATE);
			//String endTime = intent.getStringExtra(Alarm.COL_TODATE);
			
			if (matcher.matchAction(action)) 
			{
					if (POPULATE.equals(action))
					{
						//RemindMe.dbHelper.populate(Long.parseLong(alarmId), RemindMe.db);
						//execute(alarmId, titre, startTime);
						bidule();
					}
					
					if (CREATE.equals(action)) 
					{
						//execute(CREATE, alarmId, alarmMsgId, startTime, endTime);
						chargement();
					}
					
					
					if (CANCEL.equals(action)) 
					{
						//execute(CANCEL, alarmId, alarmMsgId, startTime, endTime);
						//RemindMe.dbHelper.shred(RemindMe.db);
						cancel();
					}			
			}
	}

	
	public  void chargement_debug()
	{
		
		Intent i;
		PendingIntent pi;				
		AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        
        String [] indice_tab = new String[] {"1","2","3","4","5"};
        String [] titre_tab = new String[] {"un","deux","trois","quatre","cinq"};
        long [] timestamp_tab = new long[] {1487499000000L, 1487499300000L, 1487499600000L, 1487499900000L, 1487500200000L};

        int j;
        
        long now = System.currentTimeMillis();
        
        long min = 60 * 1000; 
        timestamp_tab[0] = now + 5*min;
        timestamp_tab[1] = timestamp_tab[0] + 5*min;
        timestamp_tab[2] = timestamp_tab[1] + 5*min;
        timestamp_tab[3] = timestamp_tab[2] + 5*min;
        timestamp_tab[4] = timestamp_tab[3] + 5*min;
        
        
     	for(j = 0; j < 5; j++)
     	{
     			String sid = indice_tab [j];
     			String titre = titre_tab[j];
     			long timestamp = timestamp_tab[j];
            
				now = System.currentTimeMillis();
				
				if( now < timestamp)
				{
					i = new Intent(this, AlarmReceiver.class);
					i.putExtra("index", sid);
					i.putExtra("titre", titre);
					pi = PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
					am.set(AlarmManager.RTC_WAKEUP, timestamp, pi);
				    Log.i("************", String.valueOf(j));

				}


     	}
        
        
        Toast.makeText(AlarmService.this,  "BOOT sequence" , Toast.LENGTH_LONG).show();

	    
	}

	
	
	
	private void chargement()
	{
		
		Intent i;
		PendingIntent pi;				
		AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		Cursor c;
		
        String requete = "SELECT * FROM table_appointment ORDER BY _id ASC" ;
		Cursor Cursor = db.DB_query(requete);
		int val = Cursor.getCount();
	    Log.i("************", String.valueOf(val));
        Toast.makeText(getBaseContext(),  "BOOT sequence" , Toast.LENGTH_LONG).show();
        
        if(Cursor.moveToFirst())
        {
            do
            {
            			
						String sid = Cursor.getString(Cursor.getColumnIndex(DB_alarm.KEY_ID ));
 						String titre = Cursor.getString(Cursor.getColumnIndex(DB_alarm.COL_TITRE ));
 						String start_timestamp = Cursor.getString(Cursor.getColumnIndex(DB_alarm.COL_START_TIME ));
 						//String end_timestamp = Cursor.getString(Cursor.getColumnIndex(DB_alarm.COL_END_TIME ));
 						//String phone = Cursor.getString(Cursor.getColumnIndex(DB_alarm.COL_PHONE ));
 						//String ggnotes = Cursor.getString(Cursor.getColumnIndex(DB_alarm.COL_NOTES ));
 						//String status = Cursor.getString(Cursor.getColumnIndex(DB_alarm.COL_STATUS ));
 						//String creation = Cursor.getString(Cursor.getColumnIndex(DB_alarm.COL_CREATEDTIME ));
 						//String modification = Cursor.getString(Cursor.getColumnIndex(DB_alarm.COL_MODIFIEDTIME ));
 						//Date date_start = new Date(Long.parseLong(start_timestamp));
 						//Date date_end = new Date(Long.parseLong(end_timestamp));
 						
 						
 						long now = System.currentTimeMillis();
 						long startTime = Long.parseLong(start_timestamp);
 						
 						if( now < startTime)
 						{
 							i = new Intent(this, AlarmReceiver.class);
 							i.putExtra("index", sid);
 							i.putExtra("titre", titre);
 							pi = PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
 							am.set(AlarmManager.RTC_WAKEUP, startTime, pi);
 						}

 						
 						
            } 
            while (Cursor.moveToNext());
        }


        Cursor.close();	
	    
	}
	
	// @param args {alarmId, alarmMsgId, startTime, endTime}
	//private void execute(String action, String... args) 
	private void execute(String id, String titre, long time) 
	
	{		
				Intent i;
				PendingIntent pi;				
				AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
				
				long now = System.currentTimeMillis();
				
				i = new Intent(this, AlarmReceiver.class);
				i.putExtra("index", id);
				i.putExtra("titre", titre);

				//i.putExtra(AlarmMsg.COL_ID, c.getLong(c.getColumnIndex(AlarmMsg.COL_ID)));
				//i.putExtra(AlarmMsg.COL_ALARMID, c.getLong(c.getColumnIndex(AlarmMsg.COL_ALARMID)));
				//i.putExtra("index", id);

				int keycode = 25; //Integer.parseInt(alarmId); ////
				pi = PendingIntent.getBroadcast(this, keycode, i, PendingIntent.FLAG_UPDATE_CURRENT);
				//pi = PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);

				
				//time = c.getLong(c.getColumnIndex(AlarmMsg.COL_DATETIME));
				//time = startTime; // 1487438100000L;
				am.set(AlarmManager.RTC_WAKEUP, time, pi);

				
				
				/*diff = time-now + (long)Utils.MIN;
				
				if (CREATE.equals(action)) 
				{
					if (diff > 0 && diff < Utils.YEAR)
					{	
						am.set(AlarmManager.RTC_WAKEUP, time, pi);
					}
				}*/	

				
/*			
 * 
 * 
 * 
				String alarmId = (args!=null && args.length>0) ? args[0] : null;
				String alarmMsgId = (args!=null && args.length>1) ? args[1] : null;
				String startTime = (args!=null && args.length>2) ? args[2] : null;
				String endTime = (args!=null && args.length>3) ? args[3] : null;
				
				String status = CANCEL.equals(action) ? AlarmMsg.CANCELLED : AlarmMsg.ACTIVE;
				
				if (alarmMsgId != null) {
					c = RemindMe.db.query(AlarmMsg.TABLE_NAME, null, AlarmMsg.COL_ID+" = ?", new String[]{alarmMsgId}, null, null, null);
					
				} else {
					c = AlarmMsg.list(RemindMe.db, alarmId, startTime, endTime, status);
				}
				
				if (c.moveToFirst()) {
					long now = System.currentTimeMillis();
					long time, diff;
		//			long count = c.getCount();
		//			double MAX = alarmId!=null && count>30 ? Util.MONTH : Util.YEAR; 
					do {
						i = new Intent(this, AlarmReceiver.class);
						i.putExtra(AlarmMsg.COL_ID, c.getLong(c.getColumnIndex(AlarmMsg.COL_ID)));
						i.putExtra(AlarmMsg.COL_ALARMID, c.getLong(c.getColumnIndex(AlarmMsg.COL_ALARMID)));
						
						pi = PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
		//				pi = PendingIntent.getService(context, requestCode, intent, flags);
		
						time = c.getLong(c.getColumnIndex(AlarmMsg.COL_DATETIME));
						diff = time-now + (long)Util.MIN;
						if (CREATE.equals(action)) {
							if (diff > 0 && diff < Util.YEAR)
								am.set(AlarmManager.RTC_WAKEUP, time, pi);
							//am.setRepeating(AlarmManager.RTC_WAKEUP, triggerAtTime, interval, operation);
							
						} else if (CANCEL.equals(action)) {
							am.cancel(pi);
						}						
					} while(c.moveToNext());
				}
				c.close();		
				
				*/
	}
	
	
	private void bidule() 
	{		
		
		
//		alarmId = intent.getLongExtra("ALARMID", -1);
//		titre = intent.getStringExtra("TITRE");
//		time = intent.getLongExtra("TIME", -1);

		
		Intent i;
		PendingIntent pi;				
		AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		
		i = new Intent(this, AlarmReceiver.class);
		long keycode = alarmId; 
		i.putExtra("keycode", alarmId);
		i.putExtra("titre", titre);
		
		pi = PendingIntent.getBroadcast(this, (int) keycode, i, PendingIntent.FLAG_UPDATE_CURRENT);
		//long now = System.currentTimeMillis();
		//long time = now + 60 * 1000 * 2;
		am.set(AlarmManager.RTC_WAKEUP, time, pi);
	}
	
	
	public void cancel()
	{

		Intent i = null;
		PendingIntent pi;		
		
		//alarmId = 1;
		
		AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		
		i = new Intent(this, AlarmReceiver.class);

		
		pi = PendingIntent.getBroadcast(this, (int) alarmId, i, PendingIntent.FLAG_UPDATE_CURRENT);
		am.cancel(pi);
		
	}	
	
	/////http://android-er.blogspot.fr/2012/05/cancel-alarm-with-matching.html
	
	
	//
	//List<PendingIntent> mPendingIntentList = new ArrayList<PendingIntent>();
	// add pending intent in list
	//mPendingIntentList.add(displayIntent );
	//alarmManager.set(AlarmManager.RTC_WAKEUP, alarmDateTime, displayIntent);
    //
	    //cancel all alarms
	//    for(int idx = 0 ; idx < mPendingIntentList.size() ; idx++){
	//       alarmManager .cancel(mPendingIntentList.get(idx));
	//    }


	// PendingIntent pi = PendingIntent.getBroadcast(context, unique_id, i, 0);  In your Pending Intent you can pass a unique ID in place of requestCode
	
	//Intent intent = new Intent(this, AlarmReceiverActivity.class);
	//PendingIntent pi = PendingIntent.getBroadcast(this, 1234, intent, 0);
	//AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);

	//am.cancel(pi);
	

	//FLAG_UPDATE_CURRENT
	
	//Android - How to attach an extra to an Intent/PendingIntent 
	
/*	
	Calendar c = Calendar.getInstance();
	c.add(Calendar.SECOND, 10);
	final long afterTenSeconds = c.getTimeInMillis();
	final int requestCode = 1;

	final Intent myIntent = new Intent("MyIntentAction");
	    notificationIntent.addCategory("android.intent.category.DEFAULT");
	    notificationIntent.putExtra("message", "Hello world!");
	    
	AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
	PendingIntent broadcast = PendingIntent.getBroadcast(context, requestCode,
	                myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
	alarmManager.set(AlarmManager.RTC_WAKEUP, afterTenSeconds, broadcast);
	*/
	
	//http://luboganev.github.io/post/alarms-pending-intent/
	
	// PendingIntent pendingIntent = PendingIntent.getActivity(this, user_id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
	//am.cancel(pendingIntent);
	// https://github.com/SheldonNeilson/Android-Alarm-Clock/tree/master/src/za/co/neilson/alarm
	//https://github.com/trikita/talalarmo
	//https://github.com/CS-Worcester/TaskButler

	/// Ancal
	
}
