package com.example.service03;

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

import android.app.Activity;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.TimePicker;
import android.content.SharedPreferences.Editor;

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

//http://www.java2s.com/Open-Source/Android_Free_Code/App/assignment/com_android_deskclockAlarmDatabaseHelper_java.htm

public class MainActivity extends Activity
{
	
	TimePicker myTimePicker;
	Button b1, b2, btn_activity, buttonstartSetDialog;
	TextView textAlarmPrompt;
	
	TimePickerDialog timePickerDialog;
	
	final static int RQS_1 = 1;
	
	 public static  String MyPREFERENCES = "MyPrefs" ;
	 public static final String Name = "nameKey";
	 public static final String Phone = "phoneKey";
	 public static final String Email = "emailKey";
	   
	 public static  SharedPreferences sharedpreferences;
	  
	 Activity context = this;

	
    DatabaseHelper db;

	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
			super.onCreate(savedInstanceState);
			//setContentView(R.layout.activity_main);
			setContentView(R.layout.acceuil);
			
			/*
			textAlarmPrompt = (TextView)findViewById(R.id.alarmprompt);
	        
	        buttonstartSetDialog = (Button)findViewById(R.id.startSetDialog);
	        buttonstartSetDialog.setOnClickListener(new OnClickListener()
	        {
				@Override
				public void onClick(View v)
				{
					textAlarmPrompt.setText("");
					openTimePickerDialog(false);
				}
			});
	        
	        
	        b1 = (Button)findViewById(R.id.button);
	        b1.setOnClickListener(new View.OnClickListener() 
	        {
		           @Override
		           public void onClick(View v) 
		           {
		              addNotification();
		           }
	        });
	        
	        btn_activity = (Button)findViewById(R.id.btn_activity);
	        btn_activity.setOnClickListener(new View.OnClickListener()
	        {
		           @Override
		           public void onClick(View v) 
		           {
		        	   Intent intent = new Intent(MainActivity.this, autre_activity.class);
						startActivity(intent);
		           }
	        });
	        
	        /*
	        b2 = (Button)findViewById(R.id.btn_cancel);
	        b2.setOnClickListener(new View.OnClickListener() {
	           @Override
	           public void onClick(View v) 
	           {
	        	   PendingIntent pi;				
	       		AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
	       		pi = PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
	        		am.cancel(pi);
	           }
	        });*/
	        
	        /*
	        sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
	        SharedPreferences.Editor editor = sharedpreferences.edit();
            
            editor.putString(Name, "plouc");
            editor.putString(Phone, "zoulou");
            editor.putString(Email, "Bill");
            editor.commit();
			*/

/*
			try {
				insert_alarm_DB();
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
*/
			
			db = new DatabaseHelper(getApplicationContext());
			
			List<Alarm> allToDos = db.getAll();
			
			Cursor c = createCursor(); 
			
			
	        if (c.moveToFirst()) 
	        {
		            do {
			                //Todo td = new Todo();
			                Integer un = c.getInt((c.getColumnIndex(DatabaseHelper.COLUMN_ALARM__CREATEDTIME)));
			                String  deux = c.getString((c.getColumnIndex(DatabaseHelper.COLUMN_ALARM_NAME)));
			                //String bookName = cursor.getString(cursor.getColumnIndex("bookTitle"));
			                
		            } while (c.moveToNext());
	        }

	        
	        //http://www.java2s.com/Code/Android/UI/AlistviewexamplewherethedatacomesfromacursorandaSimpleCursorListAdapterisusedtomapeachitemtoatwolinedisplay.htm
	}
	
	public void onClick(View v)
	{
		switch (v.getId())
		{
			case R.id.imageButton1:
				startActivity(new Intent(this, SettingsActivity.class));
				break;	
		    /*		
			case R.id.imageButton2:
				startActivity(new Intent(this, AddAlarmActivity.class));
				break;
			case R.id.imageButton3:
				move(-1);
				rangeText.setText(getRangeStr());
				((SimpleCursorAdapter)getListAdapter()).changeCursor(createCursor());
				break;
			case R.id.imageButton4:
				move(+1);
				rangeText.setText(getRangeStr());
				((SimpleCursorAdapter)getListAdapter()).changeCursor(createCursor());
				break;			
	/*		case R.id.toggleButton1:
				vs.showNext();
				break;*/
		}
	}
	
	private Cursor createCursor() 
	{
		db = new DatabaseHelper(getApplicationContext());
		Cursor c = db.listNotifications();
		return c;
	}
    
	
	
	private void insert_alarm_DB() throws ParseException 
	{
		
		SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy HH:mm:ss"); // HH 24  alors que hh 12
		String dateInString = "22-11-2016 12:20:45";
		
		Date date = sdf.parse(dateInString);
		
		System.out.println(dateInString);
		System.out.println("Date - Time in milliseconds : " + date.getTime());

		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		System.out.println("Calender - Time in milliseconds : " + calendar.getTimeInMillis());
	
		
        // to convert milliseconds to Date object
		Date today1 = new Date(date.getTime());
		System.out.println("Milli seconds to date using Date class: " + today1);

       // to convert Date to Calendar
		calendar.setTime(today1);
		System.out.println("\nCalendar time: " + calendar);
		
		dateInString = "25-12-2016 12:20:45";
		date = sdf.parse(dateInString);
		long t1 = date.getTime();

		dateInString = "25-11-2016 18:00:00";
		date = sdf.parse(dateInString);
		long t2 = date.getTime();

		dateInString = "16-11-2016 16:55:40";
		date = sdf.parse(dateInString);
		long t3 = date.getTime();
		
		
		db = new DatabaseHelper(getApplicationContext());
        
		Alarm id1 = new Alarm(t1, "alarme01");
        long id = db.createToDo(id1);
        
        Alarm id2 = new Alarm(t2, "alarme02");
        id = db.createToDo(id2);
        
        Alarm id3 = new Alarm(t3, "alarme03");
        id = db.createToDo(id3);
		
		int h [] = new int [3];
		
		h[0] = 10;
	    h[1] = 14;
	    h[2] = 21;

	    Calendar cal[] = new Calendar[3];

	    for (int i = 0; i < 3; i++) 
	    {
	        cal[i] = Calendar.getInstance();
	        cal[i].set(Calendar.HOUR_OF_DAY, h[i]);
	        cal[i].set(Calendar.MINUTE, 0);
	        cal[i].set(Calendar.SECOND, 0);
	        long temps = cal[i].getTimeInMillis();
	     
	        
	        
	    //    Date aujourdhui = new Date();
	    //    aujourdhui = cal[i].getTime();
	    }

	/*
		Calendar calNow = Calendar.getInstance();
		Calendar calSet = (Calendar) calNow.clone();

		calSet.set(Calendar.HOUR_OF_DAY, hourOfDay);
		calSet.set(Calendar.MINUTE, minute);
		calSet.set(Calendar.SECOND, 0);
		calSet.set(Calendar.MILLISECOND, 0);
		
		if(calSet.compareTo(calNow) <= 0){
			//Today Set time passed, count to tomorrow
			calSet.add(Calendar.DATE, 1);
		}
		
		long temps = calSet.getTimeInMillis();
	*/	
		
	}	
	
	
	private void addNotification() 
	{
		/*
	      			NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
				         .setSmallIcon(R.drawable.ic_launcher)
				         .setContentTitle("Notifications Example")
				         .setContentText("This is a test notification");

	      Intent notificationIntent = new Intent(this, MainActivity.class);
	      PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
	         PendingIntent.FLAG_UPDATE_CURRENT);
	      builder.setContentIntent(contentIntent);

	      // Add as notification
	      NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
	      manager.notify(0, builder.build());
	  */    
	      
	      Notification n = new Notification(R.drawable.ic_launcher, "zorro", System.currentTimeMillis());
			PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), 0);
			
			n.setLatestEventInfo(getApplicationContext(), "Remind Me", "pipotron", pi);		
			
			n.flags |= Notification.FLAG_AUTO_CANCEL;		
			
			NotificationManager nm = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
			nm.notify(0 , n);
	      
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	
	private void openTimePickerDialog(boolean is24r)
	{
		Calendar calendar = Calendar.getInstance();
		
		timePickerDialog = new TimePickerDialog(
				MainActivity.this, 
				onTimeSetListener, 
				calendar.get(Calendar.HOUR_OF_DAY), 
				calendar.get(Calendar.MINUTE), 
				is24r);
		timePickerDialog.setTitle("Set Alarm Time");  
        
		timePickerDialog.show();

	}
    
    OnTimeSetListener onTimeSetListener = new OnTimeSetListener()
    {

		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

			Calendar calNow = Calendar.getInstance();
			Calendar calSet = (Calendar) calNow.clone();

			calSet.set(Calendar.HOUR_OF_DAY, hourOfDay);
			calSet.set(Calendar.MINUTE, minute);
			calSet.set(Calendar.SECOND, 0);
			calSet.set(Calendar.MILLISECOND, 0);
			
			if(calSet.compareTo(calNow) <= 0){
				//Today Set time passed, count to tomorrow
				calSet.add(Calendar.DATE, 1);
			}
			
			long temps = calSet.getTimeInMillis();
			
			setAlarm(calSet);
		}};

	private void setAlarm(Calendar targetCal)
	{

		textAlarmPrompt.setText(
				"\n\n***\n"
				+ "Alarm is set@ " + targetCal.getTime() + "\n"
				+ "***\n");
		
		Intent intent = new Intent(getBaseContext(), Receiver.class);
		PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0);
		AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
		alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent);
		
	}
	
}
