package com.example.service04;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;






import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
 
public class MainActivity extends Activity
{
 
	TextView textView1;
    DatabaseHelper db;
    ListView mListView;
    Button btn1, btn2;
 
    String[] prenoms = new String[]{
            "Antoine", "Benoit", "Cyril", "David", "Eloise", "Florent",
            "Gerard", "Hugo", "Ingrid", "Jonathan", "Kevin", "Logan",
            "Mathieu", "Noemie", "Olivia", "Philippe", "Quentin", "Romain",
            "Sophie", "Tristan", "Ulric", "Vincent", "Willy", "Xavier",
            "Yann", "Zoé"
       };
    
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
	        super.onCreate(savedInstanceState);
	        //setContentView(R.layout.activity_main);
	        setContentView(R.layout.layout_control_alarm);
	        
	        db = new DatabaseHelper(getApplicationContext());
	        
	        textView1 = (TextView)findViewById(R.id.textView1);
	        
	        btn1=(Button) findViewById(R.id.btn_start1);
			btn1.setOnClickListener(new OnClickListener() 
			{
					public void onClick(View v)
					{
						String dateInString = "16-11-2016 22:00";
					    setAlarm(dateInString, 251, 10);
					    setAlarm(dateInString, 255, 20);
					}
			});
	
	        btn2=(Button) findViewById(R.id.btn_stop2);
			btn2.setOnClickListener(new OnClickListener() 
			{
					public void onClick(View v)
					{
				    	cancelAlarm(251);
				    	cancelAlarm(255);
					}
			});
         
			
			
			SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
			Date date;
			date = null;
			
			String str = "5/4/2014 4:39:52 PM";
			try {
				date = format.parse(str);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			long millisecond1 = date.getTime();
			
			 str = "5/4/2014 4:39:52 AM";
			 try {
					date = format.parse(str);
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			long millisecond2 = date.getTime();
			
			
			date = new Date();
		      String strDateFormat = "HH:mm:ss a";
		      SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
		    String tutu = sdf.format(date);
			
    }
    
    private void setAlarm(String dateInString, int keycode, int factor)
    {
    	  SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm");
   	   	  Date date = null;
   	   	  try
	      {
   	   		  date = sdf.parse(dateInString);
		  } 
	      catch (ParseException e)
	      {
				e.printStackTrace();
		  }
	      long millis = date.getTime();
	      
	       Calendar cal = Calendar.getInstance(); 	
	       cal.setTime(date);
		
	      Intent intent = new Intent(MainActivity.this, Receiver.class);
	      intent.putExtra("valeur", keycode); // 251 ou 255
	      PendingIntent sender = PendingIntent.getBroadcast(MainActivity.this, keycode, intent, 0); // 251
		
		  long firstTime = SystemClock.elapsedRealtime();
		  
		  //firstTime = cal.getTimeInMillis();
		  //firstTime = System.currentTimeMillis();
		  
          firstTime += 3*1000; // 15 s
          AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
          am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,  firstTime, factor*1000, sender);
          
          /////////////////////Create a new PendingIntent and add it to the AlarmManager
/*          
          Intent intent = new Intent(this, RingAlarm.class);
          PendingIntent pendingIntent = PendingIntent.getActivity(this,
              12345, intent, PendingIntent.FLAG_CANCEL_CURRENT);
          AlarmManager am =
              (AlarmManager)getSystemService(Activity.ALARM_SERVICE);
          am.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(),
                  2*60*60,pendingIntent);
 */         
          //date = new Date(); 
          //date.setTime(firstTime);
          //String formattedDate=new SimpleDateFormat("MMM d, yyyy").format(date);
          //SimpleDateFormat aaasdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
          //String currentDateandTime = aaasdf.format(new Date());
		
          //cal.setTime(date);
          
          long now = System.currentTimeMillis();
          Calendar calendar = Calendar.getInstance();
	       calendar.setTimeInMillis(now);
	       String retrouve_date = sdf.format(calendar.getTime());
          
		  textView1.setText(
					"\n\n***\n"
					+ "Alarm is set@ " +  retrouve_date  + 
					  "\n"
					+ "Repeat every 15 sec\n"
					+ "***\n");
		  //avant cal.getTime()
		  
		 // Toast.makeText(getBaseContext(), "Start", Toast.LENGTH_SHORT).show();
		  
		  //targetCal.getTime()
		
          
          /*Intent i;
			PendingIntent pi;				
			AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
			i = new Intent(this, Receiver.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);
			am.set(AlarmManager.RTC_WAKEUP, time_millis, pi);
			*/
			/*
			Intent intent = new Intent(MainActivity.this, Receiver.class);
	        PendingIntent sender = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);
			long firstTime = SystemClock.elapsedRealtime();
          firstTime += 5*1000;
          AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
          am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,  firstTime, 5*1000, sender);
			
			textAlarmPrompt.setText(
					"\n\n***\n"
					+ "Alarm is set@ " + targetCal.getTime() + "\n"
					+ "Repeat every 5 minutes\n"
					+ "***\n");
		*/
	}

    private void toto()
    {
    	Intent intent = new Intent(MainActivity.this, Receiver.class);
       	PendingIntent pi = PendingIntent.getBroadcast(MainActivity.this, 251, intent, 0);
        AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
        intent.putExtra("msg", "gxgxgx");
        long time=System.currentTimeMillis();
        am.setRepeating(AlarmManager.RTC_WAKEUP,time,3000,pi);
        Log.d("lokk","click here");
    }
    
    private void cancelAlarm(int keycode)
    {
        AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(getApplicationContext(), Receiver.class);
        PendingIntent pIntent = PendingIntent.getBroadcast(this, keycode , intent, PendingIntent.FLAG_UPDATE_CURRENT); // 251
//        AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
        alarm.cancel(pIntent);
        
        pIntent = PendingIntent.getBroadcast(this, keycode , intent, PendingIntent.FLAG_UPDATE_CURRENT); // 251
//      AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
        alarm.cancel(pIntent);
    	
        Toast.makeText(getBaseContext(), "Stop", Toast.LENGTH_SHORT).show();
      
      	textView1.setText("\n\n***\n"	+ "Alarm is stopped@ " +   "***\n");
      
        
    	//Intent intent = new Intent(this, AlarmReceiverActivity.class);
    	//PendingIntent pi = PendingIntent.getBroadcast(this, 1234, intent, 0);
    	//AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
    	//am.set(AlarmManager.RTC_WAKEUP, triggerAtMillis ,pi);
    }
    
    private long time_function(String dateInString)
    {
    	
    	   SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm");
    	   Date date = null;
    	   //String dateInString;
    	   //dateInString = "25-11-2016 10:00";
	       try
	       {
				date = sdf.parse(dateInString);
		   } 
	       catch (ParseException e)
	       {
				e.printStackTrace();
		   }
	       long millis = date.getTime();
	       Calendar calendar = Calendar.getInstance();
	       calendar.setTimeInMillis(millis);
	       String retrouve_date = sdf.format(calendar.getTime());
	        
	       return(millis);
	       
	       /*dateInString = "25-11-2016 22:00";
		   try
		   {
				date = sdf.parse(dateInString);
		   } 
		   catch (ParseException e)
		   {
				e.printStackTrace();
		   }
		   long Millis02 = date.getTime();
		   Calendar calendar2 = Calendar.getInstance();
		   calendar.setTimeInMillis(Millis02);
		   String fin02 = sdf.format(calendar.getTime());
	       */ 
	        
	        
	      //  Millis = Millis / 1000;
	        
	        //String x_str = Integer.toString(x);

	        //int new_x = Integer.parseInt(x_str.substring(1));
	        
	       // 	résultat : le 15/11/2016 à 22:00:00 				soir 1480107600000
	        
	       // 15/11/2016 à 10:00:00 								matin    1480064400000
    	
    }
    
    private void insert_alarm_DB() throws ParseException 
	{
    		db = new DatabaseHelper(getApplicationContext());
		
			SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy HH:mm:ss"); // HH 24  alors que hh 12
			String dateInString = "";
			
			Date date = sdf.parse(dateInString);
	
			dateInString = "25-12-2016 12:20";
			date = sdf.parse(dateInString);
			long t1 = date.getTime();
	        long id = db.addAlarm(t1);
	
			//dateInString = "25-11-2016 18:00";
			//date = sdf.parse(dateInString);
			//long t2 = date.getTime();
			//id = db.addAlarm("Anniversaire", t2, "A");
	
			//dateInString = "16-11-2016 16:55";
			//date = sdf.parse(dateInString);
			//long t3 = date.getTime();
			//id = db.addAlarm("Perso", t3, "A");
	        
			
	 
	}	
    
    private void afficherListeNoms()
    {
        //android.R.layout.simple_list_item_1 est une vue disponible de base dans le SDK android,
        //Contenant une TextView avec comme identifiant "@android:id/text1"

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, prenoms);
        mListView.setAdapter(adapter);
    }
    

    private List<Alarm> genererAlarms()
    {
    	//Alarm(String nom, String etat, long time_milliseconds
        List<Alarm> obj = new ArrayList<Alarm>();
        obj.add(new Alarm("aqwzsx" , "actif" , 123456   ));
        obj.add(new Alarm("dickou" , "plouf" , 007   ));
        obj.add(new Alarm("alpha" , "nada" , 543   ));
        
        //tweets.add(new Alarm(Color.BLUE, "Kevin", "C'est ici que ça se passe !"   ));
        //tweets.add(new Alarm(Color.GREEN, "Logan", "Que c'est beau..."   ));
        //tweets.add(new Alarm(Color.RED, "Mathieu", "Il est quelle heure ??"  ));
        //tweets.add(new Alarm(Color.GRAY, "Willy", "On y est presque"  ));
        return obj;
    }

    private void afficherListeAlarms(List<Alarm> all)
    {
    	// OK
    	//List<Alarm> obj = genererAlarms();
    	//AlarmAdapter adapter = new AlarmAdapter(MainActivity.this, obj);
        //mListView.setAdapter(adapter);
    	
    	// ou bien ceci
        AlarmAdapter adapter = new AlarmAdapter(MainActivity.this, all);
        mListView.setAdapter(adapter);
    }
    
    private void updateTime(int hours, int mins) 
    {

        String timeSet = "";
        if (hours > 12) {
            hours -= 12;
            timeSet = "PM";
        } else if (hours == 0) {
            hours += 12;
            timeSet = "AM";
        } else if (hours == 12)
            timeSet = "PM";
        else
            timeSet = "AM";

        String minutes = "";
        if (mins < 10)
            minutes = "0" + mins;
        else
            minutes = String.valueOf(mins);

       // aTime = new StringBuilder().append(hours).append(':').append(minutes)
       //          .append(" ").append(timeSet).toString();
    }
    

}