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 temp extends Activity
{
 
    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());
        
        btn1=(Button) findViewById(R.id.btn_start1);
		btn1.setOnClickListener(new OnClickListener() 
		{
				public void onClick(View v)
				{
			    	Toast.makeText(getBaseContext(), "Click1", Toast.LENGTH_SHORT).show();
				}
		});

        btn2=(Button) findViewById(R.id.btn_stop2);
		btn2.setOnClickListener(new OnClickListener() 
		{
				public void onClick(View v)
				{
			    	Toast.makeText(getBaseContext(), "Click2 ", Toast.LENGTH_SHORT).show();
				}
		});
        
        /*
        try {
			insert_alarm_DB();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        */
        
        // creation OK
        //db.addAlarm01();
        //db.addAlarm02();
        
 /*************************************************************/       
      //  db.addAlarm03();
        
        // 25/11/2016 à 20:30:00 1480102200
        
       /* Calendar cal = Calendar.getInstance(); 	
        cal.set(Calendar.DATE, 25);
		cal.set(Calendar.MONTH, 10);
		cal.set(Calendar.YEAR, 2016);
        cal.set(Calendar.HOUR_OF_DAY, 20);
		cal.set(Calendar.MINUTE, 30);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MILLISECOND, 0);
		long conv = cal.getTimeInMillis();
		*/
		
		String dateInString = "25-11-2016 10:00";
	    long time_millis = time_function(dateInString);
	        
	       
		
		
		//cal.getTime();
		
		
//		Date date = new Date(conv);
//       SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd-hh.mm.ss");
//        System.out.println(dateformat.format(date));
		
//       Alarm id = new Alarm("nom", "etat",  conv ); //1480102200;
//       db.addAlarm04(id);
        
		/////https://www.mkyong.com/java/java-date-and-calendar-examples/
/*        
		 SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
	        String dateInString = "07/06/2013";

	        try {

	            Date date = formatter.parse(dateInString);
	            System.out.println(date);
	            System.out.println(formatter.format(date));

	        } catch (ParseException e) {
	            e.printStackTrace();
	        }
	        
	        
	        SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
	        dateInString = "31-08-1982 10:20:00";
	        Date date = null;
			try {
				date = sdf.parse(dateInString);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	        System.out.println(date); //Tue Aug 31 10:20:56 SGT 1982
	        
	        
	        // convertir la date en milliseconds puis retrouver la date
	        sdf = new SimpleDateFormat("dd-M-yyyy hh:mm");
	        dateInString = "25-11-2016 20:30";
	        try {
				date = sdf.parse(dateInString);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

	        
	        long oldMillis = date.getTime();
	        
	        Calendar calendar = Calendar.getInstance();
	        calendar.setTimeInMillis(oldMillis);
	        String fin = sdf.format(calendar.getTime());
	 */     
	        
	       
	        
	        
	       // calendar.setTimeInMillis(milliSeconds);
	       // formatter.format(calendar.getTime());
       
       // 	résultat : le 25/11/2016 à 20:30:00   1480102200
/*        
        long datetime = alarmMsg.getDateTime();
        
        int year = 2016;
        int month = 12;
        int day = 12;

        String date = year + "/" + month + "/" + day;
        
        Calendar cal = Calendar.getInstance(); 	
        
        java.util.Date utilDate = null;
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
        utilDate = formatter.parse(date);
      
		cal.setTime(utilDate);

		//at
		String[] tokens = c.getString(4).split(":"); //hh:mm
		cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(tokens[0]));
		cal.set(Calendar.MINUTE, Integer.parseInt(tokens[1]));
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MILLISECOND, 0);
		
		alarmMsg.setDateTime(cal.getTimeInMillis());
        
        // test lecture
        
        //https://github.com/florent37/TutosAndroidFrance/blob/master/ListViewSample/app/src/main/java/tutosandroidfrance/com/listviewsample/MainActivity.java
        
        ArrayList<String> tab = new ArrayList<String>();
       
        List<Alarm> all = db.getAll();
        for (Alarm todo : all)
        {
            Log.d("ToDo", todo.get_nom());
            
            tab.add(todo.get_nom());
            
        }
	
       
        mListView = (ListView) findViewById(R.id.listView);
        
        //afficherListeNoms();
        afficherListeAlarms(all);
*/ 
        
        
/*************************************************************/       
                
		
     
       /* 
        Todo todo1 = new Todo("dgqdsgsdgg", 0);
        long todo1_id = db.createToDo(todo1);
        
         todo1 = new Todo("zorro", 0);
         todo1_id = db.createToDo(todo1);
        
        List<Todo> allToDos = db.getAllToDos();
        for (Todo todo : allToDos)
        {
            Log.d("ToDo", todo.getNote());
        }
       
        */
/*  
   
        Tag tag1 = new Tag("Shopping");
        Tag tag2 = new Tag("Important");
        Tag tag3 = new Tag("Watchlist");
        Tag tag4 = new Tag("Androidhive");
 
        // Inserting tags in db
        long tag1_id = db.createTag(tag1);
        long tag2_id = db.createTag(tag2);
        long tag3_id = db.createTag(tag3);
        long tag4_id = db.createTag(tag4);

        Log.d("Tag Count", "Tag Count: " + db.getAllTags().size());
/*
        // Creating ToDos
        Todo todo1 = new Todo("iPhone 5S", 0);
        Todo todo2 = new Todo("Galaxy Note II", 0);
        Todo todo3 = new Todo("Whiteboard", 0);
 
        Todo todo4 = new Todo("Riddick", 0);
        Todo todo5 = new Todo("Prisoners", 0);
        Todo todo6 = new Todo("The Croods", 0);
        Todo todo7 = new Todo("Insidious: Chapter 2", 0);
 
        Todo todo8 = new Todo("Don't forget to call MOM", 0);
        Todo todo9 = new Todo("Collect money from John", 0);
 
        Todo todo10 = new Todo("Post new Article", 0);
        Todo todo11 = new Todo("Take database backup", 0);
 
        // Inserting todos in db
        // Inserting todos under "Shopping" Tag
        long todo1_id = db.createToDo(todo1, new long[] { tag1_id });
        long todo2_id = db.createToDo(todo2, new long[] { tag1_id });
        long todo3_id = db.createToDo(todo3, new long[] { tag1_id });
 
        // Inserting todos under "Watchlist" Tag
        long todo4_id = db.createToDo(todo4, new long[] { tag3_id });
        long todo5_id = db.createToDo(todo5, new long[] { tag3_id });
        long todo6_id = db.createToDo(todo6, new long[] { tag3_id });
        long todo7_id = db.createToDo(todo7, new long[] { tag3_id });
 
        // Inserting todos under "Important" Tag
        long todo8_id = db.createToDo(todo8, new long[] { tag2_id });
        long todo9_id = db.createToDo(todo9, new long[] { tag2_id });
 
        // Inserting todos under "Androidhive" Tag
        long todo10_id = db.createToDo(todo10, new long[] { tag4_id });
        long todo11_id = db.createToDo(todo11, new long[] { tag4_id });
 
        Log.e("Todo Count", "Todo count: " + db.getToDoCount());
 
        // "Post new Article" - assigning this under "Important" Tag
        // Now this will have - "Androidhive" and "Important" Tags
        db.createTodoTag(todo10_id, tag2_id);
 
        // Getting all tag names
        Log.d("Get Tags", "Getting All Tags");
 
        List<Tag> allTags = db.getAllTags();
        for (Tag tag : allTags) {
            Log.d("Tag Name", tag.getTagName());
        }
 
        // Getting all Todos
        Log.d("Get Todos", "Getting All ToDos");
 
        List<Todo> allToDos = db.getAllToDos();
        for (Todo todo : allToDos) {
            Log.d("ToDo", todo.getNote());
        }
 
        // Getting todos under "Watchlist" tag name
        Log.d("ToDo", "Get todos under single Tag name");
 
        List<Todo> tagsWatchList = db.getAllToDosByTag(tag3.getTagName());
        for (Todo todo : tagsWatchList) {
            Log.d("ToDo Watchlist", todo.getNote());
        }
 
        // Deleting a ToDo
        Log.d("Delete ToDo", "Deleting a Todo");
        Log.d("Tag Count", "Tag Count Before Deleting: " + db.getToDoCount());
 
        db.deleteToDo(todo8_id);
 
        Log.d("Tag Count", "Tag Count After Deleting: " + db.getToDoCount());
 
        // Deleting all Todos under "Shopping" tag
        Log.d("Tag Count",
                "Tag Count Before Deleting 'Shopping' Todos: "
                        + db.getToDoCount());
 
        db.deleteTag(tag1, true);
 
        Log.d("Tag Count",
                "Tag Count After Deleting 'Shopping' Todos: "
                        + db.getToDoCount());
 
        // Updating tag name
        tag3.setTagName("Movies to watch");
        db.updateTag(tag3);
 
        // Don't forget to close database connection
        db.closeDB();
         
        
    */   
         
    }
    
    private void setAlarm(String dateInString)
    {
    	  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();
		
	      Intent intent = new Intent(temp.this, Receiver.class);
	      PendingIntent sender = PendingIntent.getBroadcast(temp.this, 0, intent, 0);
		
		  long firstTime = SystemClock.elapsedRealtime();
          firstTime += 15*1000; // 15 s
          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");
		  */
		
          
          /*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 cancelAlarm()
    {
        //Intent intent = new Intent(getApplicationContext(), MyAlarmReceiver.class);
        //final PendingIntent pIntent = PendingIntent.getBroadcast(this, MyAlarmReceiver.REQUEST_CODE,
        //intent, PendingIntent.FLAG_UPDATE_CURRENT);
        //AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
        //alarm.cancel(pIntent);
    	
    	//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>(temp.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(temp.this, all);
        mListView.setAdapter(adapter);
}
    

}