package com.example.date_time_picker01;


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.ListActivity;
import android.app.PendingIntent;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.SimpleCursorAdapter.ViewBinder;
import android.widget.Toast;

//http://www.android-examples.com/change-datepickerdialog-theme-in-android-using-dialogfragment/

public class MainActivity extends ListActivity
{

	
	 	DatabaseHelper db;
	 	ListView mListView;
	 	SimpleCursorAdapter dataAdapter;
		TextView rangeText;
	  
	  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é"
	       };
	 
	  public final Calendar cal = Calendar.getInstance();
	  public final Date dt = new Date();
	  //private String[] monthArr;
	  
	  String[] monthArr = new String[]{ "Month","Jan", "Feb", "Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"  };
	  
	  
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main_bis);
		
		rangeText = (TextView) findViewById(R.id.range_tv);
		
		db = new DatabaseHelper(getApplicationContext());
		
		
		int r = 1; //Tools.getDateRange();
		switch(r)
		{
			case 3: // Yearly
				cal.set(Calendar.MONTH, 0);
				
			case 2: // Monthly
				cal.set(Calendar.DATE, 1);
				
			case 1: // Weekly
				if (r==1) cal.set(Calendar.DATE, cal.getFirstDayOfWeek());
				
			case 0: // Daily
		        cal.set(Calendar.HOUR_OF_DAY, 0);
		    	cal.set(Calendar.MINUTE, 0);
				cal.set(Calendar.SECOND, 0);
				cal.set(Calendar.MILLISECOND, 0);
		}
			
		rangeText.setText(getRangeStr()); //getRangeStr()
		
		
		String dateInString = "28-11-2016 22:00";
		long  time_millis = convertir_date_timestamp(dateInString);
	    long now = System.currentTimeMillis(); 
	    String NAME = "blase";
	    String FROMDATE =  "toto";
	    String TODATE =  "titi";
	    long DATETIME =  time_millis;
	    String STATUS = "active";
	    long CREATEDTIME =  now ;
	    long MODIFIEDTIME =  now ;
	    //db.insert_alarm(NAME, FROMDATE, TODATE, DATETIME, STATUS, CREATEDTIME, MODIFIEDTIME);
	   
		
	    dateInString = "15-9-2018 12:30";
		time_millis = convertir_date_timestamp(dateInString);
	    now = System.currentTimeMillis(); 
	    NAME = "blase";
	    FROMDATE =  "toto";
	    TODATE =  "titi";
	    DATETIME =  time_millis;
	    STATUS = "active";
	    CREATEDTIME =  now ;
	    MODIFIEDTIME =  now ;
	    //db.insert_alarm(NAME, FROMDATE, TODATE, DATETIME, STATUS, CREATEDTIME, MODIFIEDTIME);
	   
	    dateInString = "15-9-2018 0:30";
		time_millis = convertir_date_timestamp(dateInString);
	    now = System.currentTimeMillis(); 
	    NAME = "blase";
	    FROMDATE =  "toto";
	    TODATE =  "titi";
	    DATETIME =  time_millis;
	    STATUS = "active";
	    CREATEDTIME =  now ;
	    MODIFIEDTIME =  now ;
	    //db.insert_alarm(NAME, FROMDATE, TODATE, DATETIME, STATUS, CREATEDTIME, MODIFIEDTIME);
	    
		 
		  // creation OK
	      // db.addAlarm01();
	      // db.addAlarm02();
	        
	        
	       // db.addAlarm03();
	        
	      //  mListView = (ListView) findViewById(R.id.listView);
	        
	     /*   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());
	            
	        }*/
	        
	        //afficherListeNoms();
	        //displayListView();
	        //afficherListeAlarms(all);
		 
	}
	
	
	 private long convertir_date_timestamp(String dateInString)
	    {
	    	  SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy HH:mm"); // 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.getTime();
		}

	/******************************  fonctionne avec activity_main modifié ***************************************************/
	
	private void displayListView()
 	{
			Cursor cursor = db.DB_All_Alarms();

			int nbre = cursor.getCount();
			
			String[] col = new String[] {
							  db.COL_NAME,
							  db.COL_FROMDATE,
							};

			int[] to = new int[] { 
	 							R.id.secondLine,
	 							R.id.firstLine,
	 						};

		 	dataAdapter = new SimpleCursorAdapter(this, R.layout.row01, cursor, col, to, 0);
	
		 	ListView listView = (ListView) findViewById(R.id.listView);
		 
		 	listView.setAdapter(dataAdapter);

		 	listView.setOnItemClickListener(new OnItemClickListener() 
			{
					   @Override
					   public void onItemClick(AdapterView<?> listView, View view, int position, long id) 
					   {
							   Cursor cursor = (Cursor) listView.getItemAtPosition(position);
							   Toast.makeText(getApplicationContext(), String.valueOf(position) , Toast.LENGTH_LONG).show();
							   String pipo = cursor.getString(cursor.getColumnIndex("from_date"));
							   Intent intent = new Intent(MainActivity.this, edit_alarm.class);  
							   intent.putExtra("parametre", pipo);
							   startActivity(intent);
					   }
			});

 	}

	
	/******************************  essai ***************************************************/
	
	
	private Cursor createCursor()
	{
		//Cursor c = RemindMe.dbHelper.listNotifications(db, cal.getTimeInMillis()+move(+1), cal.getTimeInMillis()+move(-1));
		
		// Cursor c = db.rawQuery("SELECT * FROM symbol AS s, quote AS q WHERE q.pair = ? || s.code AND s.isTracked = 1", 
        //         new String[]{baseCurrency});
		
		Cursor c = db.DB_All_Alarms();
		
		startManagingCursor(c);
		return c;
	}
    
    @Override
	protected void onResume() 
    {
		super.onResume();

		//https://fr.scribd.com/document/102525135/Android-Adapters-An-Introduction   ++++++ interessant
		//Développez pour Android
		//Par Cyril Mottier,Ludovic Perrier
		
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(
				this, 
				R.layout.row_bis, 
				createCursor(), 
				new String[]{ DatabaseHelper.COL_NAME, DatabaseHelper.COL_FROMDATE, DatabaseHelper.COL_TODATE, DatabaseHelper.COL_DATETIME, DatabaseHelper.COL_STATUS }, 
				new int[]{R.id.msg_tv, R.id.year_tv, R.id.month_tv, R.id.date_tv, R.id.time_tv}, 0);
		
		adapter.setViewBinder(new ViewBinder() 
		{
				@Override
				public boolean setViewValue(View view, Cursor cursor, int columnIndex)
				{
						if (view.getId() == R.id.msg_tv) return false;
		
						TextView tv = (TextView)view;
						//long time = cursor.getLong(columnIndex);
						//dt.setTime(time);
						switch(view.getId()) 
						{
							case R.id.year_tv:
								tv.setText("papa");
								break;
							case R.id.month_tv:
								tv.setText("lulu");
								break;
							case R.id.date_tv:
								tv.setText("coco");
								break;
						}
						return true;
			}
		});
		
		setListAdapter(adapter);
		
		
	}
	
	/****************************************************************************************/
	
	@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);
	}
	
	
	public void onClick(View v) 
	{
		switch (v.getId())
		{
			case R.id.imageButton1:
				startActivity(new Intent(this, Settings.class));
				break;		
			case R.id.imageButton2:
				startActivity(new Intent(this, AddAlarm.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;	
						
		}
	}
	
	private String move(int step)
	{
		switch(Tools.getDateRange()) 
		{
			case 0:
				cal.add(Calendar.DATE, 1*step); // jour
				break;		
			case 1:
				cal.add(Calendar.DATE, 7*step); // semaine = 7 jours
				break;
			case 2:
				cal.add(Calendar.MONTH, 1*step); // mois
				break;
			case 3:
				cal.add(Calendar.YEAR, 1*step); // année
				break;			
		}
		return "";
	}    
	
	private String getRangeStr()
	{
			int date = cal.get(Calendar.DATE);
			int month = cal.get(Calendar.MONTH);
			int year = cal.get(Calendar.YEAR);
			dt.setTime(System.currentTimeMillis());
			
			switch(Tools.getDateRange()) 
			{
				case 0: // Daily
					if (date==dt.getDate() && month==dt.getMonth() && year==dt.getYear()+1900) return "Today";
					else return date+" "+monthArr[month+1];
					
				case 1: // Weekly
					return date+" "+monthArr[month+1] + move(+1) + " - " + cal.get(Calendar.DATE)+" "+monthArr[cal.get(Calendar.MONTH)+1] + move(-1);
					
				case 2: // Monthly
					return monthArr[month+1]+" "+year;
					
				case 3: // Yearly
					return year+"";
			}
			return null;
	}
	
	
	/*******************************************************************/
	
	 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);
	}
	
}
