package com.androidbegin.buttonclicktutorial;


import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.RelativeLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;


import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.app.NotificationManager;
//import android.support.v4.app.NotificationCompat;
import android.view.View;
import android.content.Context;
import android.app.PendingIntent;
import android.content.Intent;
import android.net.Uri;


//https://sites.google.com/site/androidcheckinfo/android-alarm-example/android-alarm-for-specific-date

//http://android-er.blogspot.fr/2015/06/generate-alarm-notification-and.html

//tp://android-er.blogspot.fr/2010/10/simple-example-of-alarm-service-using.html/

public class datepicker extends Activity 
{
	
	 TextView date_infos; 
	 Button valide;
	
	 private int year;
	 private int month;
	 private int day;
	 private int hour;
	 private int min;
	 
	 private Button btn_start, btn_stop;
	 private DbAdapter dbHelper;
	 private SimpleCursorAdapter dataAdapter;
		
	 Ringtone ringtone;
	 
	 DatePicker pickerDate;
	 TimePicker pickerTime;
	 Button buttonSetAlarm;

	 final static int RQS_1 = 1;

	 
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
	        super.onCreate(savedInstanceState);
	        //setContentView(R.layout.datepicker_view);
	        //setContentView(R.layout.picker01);
	    	
	        //TimePicker TimePicker = (TimePicker) findViewById(R.id.timePicker1);
	        //TimePicker.setIs24HourView(true); // to set 24 hours mode
	        
	        
	        setContentView(R.layout.alarm_layout);
	        
			pickerTime = (TimePicker)findViewById(R.id.timePicker);
			pickerDate = (DatePicker)findViewById(R.id.datePicker);

	        
			pickerTime.setIs24HourView(true); // to set 24 hours mode

			
			Calendar now = Calendar.getInstance();

			pickerDate.init(
							now.get(Calendar.YEAR), 
							now.get(Calendar.MONTH), 
							now.get(Calendar.DAY_OF_MONTH), 
							null);
		
			pickerTime.setCurrentHour(now.get(Calendar.HOUR_OF_DAY));
			pickerTime.setCurrentMinute(now.get(Calendar.MINUTE));
		
			buttonSetAlarm = (Button)findViewById(R.id.btn_setalarm);
			buttonSetAlarm.setOnClickListener(new OnClickListener()
			{

				@Override
				public void onClick(View arg0) 
				{
					Calendar current = Calendar.getInstance();
					Calendar cal = Calendar.getInstance();
					cal.set(pickerDate.getYear(), 
							pickerDate.getMonth(), 
							pickerDate.getDayOfMonth(), 
							pickerTime.getCurrentHour(), 
							pickerTime.getCurrentMinute(), 
							00);
				
				if(cal.compareTo(current) <= 0)
				{
				    Toast.makeText(getApplicationContext(), "Invalid Date/Time", Toast.LENGTH_LONG).show();
				}
				else
				{
					setAlarm(cal);
				}
				
			}});

	        
/*	    	
	        
	        config();
	        
            
            btn_start = (Button) findViewById(R.id.btn_start);
            btn_stop = (Button) findViewById(R.id.btn_stop);

            Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
            if (alarmUri == null)
            {
                alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            }
            ringtone = RingtoneManager.getRingtone(datepicker.this, alarmUri);
             //ringtone = RingtoneManager.getRingtone(this, Uri.parse(ringtone_uri));
            
            btn_start.setOnClickListener(new OnClickListener()
	        {
	            @Override
	            public void onClick(View v) 
	            {
	                // ringtone = RingtoneManager.getRingtone(datepicker.this, alarmUri);
	            	sendNotification();
	                ringtone.play();
	            }
	        });
	        
            btn_stop.setOnClickListener(new OnClickListener()
	        {
	            @Override
	            public void onClick(View v) 
	            {
	               // Ringtone ringtone = RingtoneManager.getRingtone(datepicker.this, alarmUri);
	            	ringtone.stop();
	            }
	        });
*/	       
   }
    
    
    public void sendNotification()
    {

/*		OK
    	NotificationCompat.Builder mBuilder =
    	 new NotificationCompat.Builder(this)
    	 .setSmallIcon(R.drawable.ic_launcher)
    	 .setContentTitle("My notification")
    	 .setContentText("Hello World!");
    	NotificationManager mNotificationManager = 	(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    	mNotificationManager.notify(001, mBuilder.build());
 */   	 
    	
		Intent intent = new Intent();
		PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
		Notification noti = new Notification.Builder(this)
		.setTicker("Ticker Title")
		.setContentTitle("Content Title")
		.setContentText("Notification content.")
		.setSmallIcon(R.drawable.ic_launcher)
		.setContentIntent(pIntent).getNotification();
		
		noti.flags=Notification.FLAG_AUTO_CANCEL;
		NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		notificationManager.notify(0, noti); 
    	
    	
    	}
   /* 
    private final void createNotification()
    {
    	   final NotificationManager mNotification = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    	 
    	       final Intent launchNotifiactionIntent = new Intent(this, TutoNotificationHomeActivity.class);
    	   final PendingIntent pendingIntent = PendingIntent.getActivity(this,
    	               REQUEST_CODE, launchNotifiactionIntent,
    	               PendingIntent.FLAG_ONE_SHOT);
    	 
    	   Notification.Builder builder = new Notification.Builder(this)
    	       .setWhen(System.currentTimeMillis())
    	       .setTicker("notificationTitle")
    	       .setSmallIcon(R.drawable.notification)
    	       .setContentTitle(getResources().getString(R.string.notification_title))
    	       .setContentText(getResources().getString(R.string.notification_desc))
    	       .setContentIntent(pendingIntent);
    	 
    	   mNotification.notify(NOTIFICATION_ID, builder.build());
    */	   
    	   /*
    	    Récupération d’une instance de la classe NotificationManager
			Créer l’intent correspondant à la vue lancée lors du clic sur la notification
			Créer un pending intent décrivant l’intent précédant
			Créer une notification à l’aide d’un Builder, en spécifiant le contexte, le délais de déclenchement de la notification, le titre de la notification, l’icone, le titre et la description du contenu de la notification, l’intent à lier à la notification.
			Le déclenchement de la notification s’effectue à l’aide de la méthode notify 
    	     
    /*	    
    	   
    	   }
    */
    
    
    public void config()
    {
    	
    		setContentView(R.layout.alarm_layout);
    	
			pickerTime = (TimePicker)findViewById(R.id.timePicker);
			pickerDate = (DatePicker)findViewById(R.id.datePicker);
			
			//pickerDate.setI
			
			//pickerDate.setIs24HourView(true); // to set 24 hours mode
	        
			
			Calendar now = Calendar.getInstance();

			pickerDate.init(
							now.get(Calendar.YEAR), 
							now.get(Calendar.MONTH), 
							now.get(Calendar.DAY_OF_MONTH), 
							null);
		
			pickerTime.setCurrentHour(now.get(Calendar.HOUR_OF_DAY));
			pickerTime.setCurrentMinute(now.get(Calendar.MINUTE));
		
			buttonSetAlarm = (Button)findViewById(R.id.btn_setalarm);
			buttonSetAlarm.setOnClickListener(new OnClickListener()
			{

				@Override
				public void onClick(View arg0) 
				{
					Calendar current = Calendar.getInstance();
					Calendar cal = Calendar.getInstance();
					cal.set(pickerDate.getYear(), 
							pickerDate.getMonth(), 
							pickerDate.getDayOfMonth(), 
							pickerTime.getCurrentHour(), 
							pickerTime.getCurrentMinute(), 
							00);
				
				if(cal.compareTo(current) <= 0)
				{
				    Toast.makeText(getApplicationContext(), "Invalid Date/Time", Toast.LENGTH_LONG).show();
				}
				else
				{
					setAlarm(cal);
				}
				
			}});

    	
    	
    }
    
    
	private void setAlarm(Calendar targetCal)
	{

	    Toast.makeText(getApplicationContext(), "Set alarm", Toast.LENGTH_LONG).show();

		
		//info.setText("\n\n***\n"+ "Alarm is set@ " + targetCal.getTime() + "\n"	+ "***\n");
		
		Intent intent = new Intent(getBaseContext(), AlarmReceiver.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);	  
	}

    
    
    
  
   
        
    
}