package com.example.appli_calendar06;



import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.format.DateFormat;

import android.content.Context;
import android.database.Cursor;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class DB_calendar extends SQLiteOpenHelper 
{
	//define all the constants
    public static final String DATABASE_NAME="calendar01";
    public static final String TABLE = "table_calendar";
    public static final int DATABASE_VERSION = 1;
    
    public static final String KEY_ID = "_id";
    public static final String COL_NAME = "name";
    public static final String COL_FROMDATE = "from_date";
	public static final String COL_TODATE = "to_date";
	public static final String COL_DATETIME = "datetime";
	public static final String COL_STATUS = "status";
	public static final String COL_CREATEDTIME = "created_time";
	public static final String COL_MODIFIEDTIME = "modified_time";
	public static final String COL_RULE = "rule";
	public static final String COL_INTERVAL = "interval";
	public static final String COL_SOUND = "sound";
	public static final String COL_INFO = "info";
	public static final String COL_CREATED_AT = "created_at";
    
	public static final String COL_MESSAGE = "message";
	public static final String COL_REMINDER = "reminder";
	public static final String COL_END = "end";
    
	
	public  static final String CREATE_TABLE = "CREATE TABLE "
	            + TABLE + "(" 
	    		+ KEY_ID + " INTEGER PRIMARY KEY,"
	    		+ COL_NAME + " TEXT," 
	    		+ COL_FROMDATE + " DATE," 
	    		+ COL_TODATE + " DATE," 
	    		+ COL_DATETIME + " INTEGER," 
	    		+ COL_STATUS + " TEXT," 
	            + COL_CREATEDTIME + " INTEGER," 
	            + COL_MODIFIEDTIME + " INTEGER,"
	            + COL_CREATED_AT + " DATETIME" + ")";
	
	public static final String DEFAULT_DATE_FORMAT = "yyyy-M-d";
	
	public static final SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
	
	
	
    public DB_calendar(Context context) 
    {
    	//create the database
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db)
    {
    	//create the table
        //db.execSQL(CREATE_TABLE);
       
    	String req = "CREATE TABLE table_calendar ( `_id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, `message` TEXT NOT NULL, `reminder` TEXT NOT NULL, `end` TEXT )";
		  db.execSQL(req);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
    	//onUpgrade remove the existing table, and recreate and populate new data
        db.execSQL("DROP TABLE IF EXISTS "+ TABLE);
        onCreate(db);
        
       // db.execSQL("DROP TABLE IF EXISTS "+ DATABASE_NAMES);
       // onCreate(db);
    }

    
    public long insert_calendar(String MESSAGE, String REMINDER, String END)
    {
    	
    		SQLiteDatabase db = this.getWritableDatabase();
			ContentValues vals = new ContentValues();
			vals.put(COL_MESSAGE, MESSAGE);
			vals.put(COL_REMINDER, REMINDER );
			vals.put(COL_END, END );
			long id = db.insert(TABLE, null, vals);
			return id;
    	
    }
    
    
    public List<EventObjects> getAllFutureEvents()
    {
    	SQLiteDatabase db = this.getWritableDatabase();
    	
        Date dateToday = new Date();
        SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
        String now = df.format(dateToday);
        
        List<EventObjects> events = new ArrayList<>();
        String query = "select * from table_calendar";
        Cursor cursor = db.rawQuery(query, null);
        if(cursor.moveToFirst())
        {
	            do{
	                int id = cursor.getInt(0);
	                String message = cursor.getString(cursor.getColumnIndexOrThrow("message"));
	                String startDate = cursor.getString(cursor.getColumnIndexOrThrow("reminder"));
	                String end = cursor.getString(cursor.getColumnIndexOrThrow("end"));
	              
	                startDate = "27-12-2016";
/*	              
	            	Calendar cal = Calendar.getInstance();
	            	cal.set(Calendar.YEAR, 2016);
	                cal.set(Calendar.MONTH, 11);
	                cal.set(Calendar.DAY_OF_MONTH, 27);
	                cal.set(Calendar.HOUR_OF_DAY, 0);
	                cal.set(Calendar.MINUTE, 0);
	                cal.set(Calendar.SECOND, 0);
	                cal.set(Calendar.MILLISECOND, 0);
	                
	                Date d = cal.getTime();
	                String build = df.format(d);
*/	                
	                boolean test ; 
	                
	                if( startDate.equals(now) )
	                {
	                	test = true;
	                }
	                else
	                {
	                	test = false;
	                }
	                
	                
	                Date aujourdhui = new Date();
	                SimpleDateFormat formater = null;
	                formater = new SimpleDateFormat("dd-MM-yyyy");
	              
	                String aqw = formater.format(aujourdhui);
	                
	                Date reminderDate = convertir_String_to_date(startDate);
	                if(reminderDate.after(dateToday) || reminderDate.equals(dateToday))
	                {
	                    events.add(new EventObjects(id, message, reminderDate));
	                }
	            } while (cursor.moveToNext());
        }
        
        cursor.close();
        return events;
    }
    
    private Date convertStringToDate(String dateInString)
    {
        SimpleDateFormat format = new SimpleDateFormat("d-MM-yyyy");
        Date date = null;
        try {
            date = format.parse(dateInString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
    
    private Date convertir_String_to_date(String dateInString)
	
    {
    	  SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); // HH format 24H (0:23) alors que hh sur 12H
   	   	  Date date = null;
   	   	  try
	      {
   	   		  date = sdf.parse(dateInString);
		  } 
	      catch (ParseException e)
	      {
				e.printStackTrace();
		  }
	      
   	   	  return date;
	}
    
    
    public static String dateToString(Date date, boolean leadingZeros) {
        String dateStr;

        if (date == null) {
          dateStr = "";
        } else {
          GregorianCalendar calendar = new GregorianCalendar();
          calendar.setTime(date);

          int day = calendar.get(GregorianCalendar.DAY_OF_MONTH);
          int month = calendar.get(GregorianCalendar.MONTH) + 1;

          dateStr = (leadingZeros && day < 10 ? "0" : "") + day + ". "
              + (leadingZeros && month < 10 ? "0" : "") + month + ". "
              + calendar.get(GregorianCalendar.YEAR) + ".";
        }

        return dateStr;
      }
    
    
   
    
    
   
    
  
    
   
    
    
   
    
    
   
}


