package com.androidbegin.buttonclicktutorial;


import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.net.ParseException;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

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

public class agenda02 extends Activity 
{
    private static final String TAG = MainActivity.class.getSimpleName();
    private ImageView previousDay;
    private ImageView nextDay;
    private TextView DisplayDate;
    private Calendar cal = Calendar.getInstance();
    private DatabaseQuery mQuery;
    private RelativeLayout mLayout;
    private int eventIndex;
    
    TextView mEventView;
    TextView tv; 
    
    Calendar cal_start = Calendar.getInstance();
    Calendar cal_end = Calendar.getInstance();
    
	DB_alarm db;
	private SQLiteDatabase dataBase;
	
	private Calendar cal_display = Calendar.getInstance();
    
	private int ptr = 0;
	private boolean flag = false;
	
	int[] id_table = {0, 50, 100, 150, 200, 250, 300, 350 , 400 , 450, 500, 550 , 650 , 700 , 750 , 800 , 850, 900 , 950 , 1000 };
    
	int store_nb_appointment = 0;
	
	final static ArrayList<appointment> appointment_liste = new ArrayList<appointment>();
	
	String date_selection = "";
	long timestamp; 
	
	@Override
    protected void onCreate(Bundle savedInstanceState)
    {
		        super.onCreate(savedInstanceState);
		        setContentView(R.layout.agenda_view);
		        db = new DB_alarm(getApplicationContext());
		        
		        
		        ActionBar actionBar = getActionBar();
		        getActionBar().setHomeButtonEnabled(true);
		        getActionBar().setDisplayHomeAsUpEnabled(true);
		        setTitle("Voir rendez-vous");

		        
		        
		        //Toast.makeText(getApplicationContext(), "TRACE DEBUG", Toast.LENGTH_SHORT).show();
		        
		        //setContentView(R.layout.new_view);
		    	//Toast.makeText(getApplicationContext(), "Debug agenda02", Toast.LENGTH_SHORT).show();
		        mQuery = new DatabaseQuery(this);
		        mLayout = (RelativeLayout)findViewById(R.id.left_event_column);
		        //eventIndex = mLayout.getChildCount();
		        
		        Bundle extras = getIntent().getExtras();
				date_selection = extras.getString("EXTRA");
				//DisplayDate=(TextView)findViewById(R.id.display_current_date); 
				//DisplayDate.setText(date_selection);
				
				//cal_display
				String[]tmp = date_selection.split(" ");
			    int jour = Integer.parseInt(tmp[0]);
			    int mois = Integer.parseInt(tmp[1]);
			    int annee = Integer.parseInt(tmp[2]);
			    mois = mois - 1;
			    cal_display.set(annee, mois, jour, 0, 0, 0); 
			    cal_display.set(Calendar.MILLISECOND, 0);
		        
				DisplayDate=(TextView)findViewById(R.id.display_current_date);
				DisplayDate.setText(displayDateInString(cal_display.getTime()));
				
				
				
				
				Calendar cal_actif = Calendar.getInstance();
				tmp = date_selection.split(" ");
			    jour = Integer.parseInt(tmp[0]);
			    mois = Integer.parseInt(tmp[1]);
			    annee = Integer.parseInt(tmp[2]);
			    mois = mois - 1;
				cal_actif.set(annee, mois, jour, 0, 0, 0); 
				cal_actif.set(Calendar.MILLISECOND, 0);
		        timestamp = cal_actif.getTimeInMillis();
		        
		        gestion_appointment(timestamp);
		        
		        
		        
		        previousDay = (ImageView)findViewById(R.id.previous_day);
		        nextDay = (ImageView)findViewById(R.id.next_day);
		        
		        previousDay.setOnClickListener(new View.OnClickListener()
		        {
		            @Override
		            public void onClick(View v)
		            {
		                previousCalendarDate();
		            }
		        });
		        
		        
		        nextDay.setOnClickListener(new View.OnClickListener() 
		        {
		            @Override
		            public void onClick(View v)
		            {
		                nextCalendarDate();
		            }
		        });
    }
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) 
	{ 
	    switch (item.getItemId())
	    {
	        case android.R.id.home:
	            this.finish();
	            return true;
	            default:
	            return super.onOptionsItemSelected(item);
	    }
	}
    
	@Override
	protected void onResume() 
	{
			super.onResume();
			appointment_liste.clear();
			
			int cpt = 0;
    		for(int i = 0; i < store_nb_appointment; i++)
    		{
    			int elem1 = cpt * 50;
				int elem2 = elem1 + 50;
				cpt = cpt + 2;
				
				// 0 * 50 = 0  puis  0 * 50 + 50 = 50  
					// 2 * 50 = 100 puis 2* 50 + 50 = 150
					// 4 * 50 = 200 puis 4 * 50 + 50 = 250				
    			
    			  View namebar = mLayout.findViewById(elem1);
    		      ViewGroup parent = (ViewGroup) namebar.getParent();
    		      if (parent != null) 
    		      {
    		         parent.removeView(namebar);
    		     }
    		     
    		      namebar = mLayout.findViewById(elem2);
    		      parent = (ViewGroup) namebar.getParent();
    		      if (parent != null) 
    		      {
    		         parent.removeView(namebar);
    		     }

    		}
			
			gestion_appointment(timestamp);
			//Toast.makeText(getApplicationContext(), "Refresh", Toast.LENGTH_SHORT).show();
			
	}		
	
    private void gestion_appointment(long timestamp)
    {
    	

    		//long timestamp =  1484780400000L;  // 19 01 2017 
    		String stimestamp = String.valueOf(timestamp);
         
    		// lire la table 
    		//	String requete = "SELECT * FROM table_appointment WHERE datetime >= " + max + " AND datetime <= " + min + " ORDER BY datetime ASC" ;
    		String requete = "SELECT * FROM table_appointment WHERE date = " + stimestamp ;
     	
    		Cursor Cursor = db.DB_query(requete);
    		int val = Cursor.getCount();
    		store_nb_appointment = val;
    		int cpt = 0;
    		int index = 1;
    		
    		if(val != 0)
    		{
        		eventIndex = mLayout.getChildCount();
        		flag = true;
    			
        		
 				if (Cursor.moveToFirst()) 
 				{
	 					do 
	 					{
	 							
	 							//
	 							// 1 2  id_table[cpt]
	 						    // 3 4 
	 						
	 							String sid = Cursor.getString(Cursor.getColumnIndex(DB_alarm.KEY_ID ));
		 						String titre = Cursor.getString(Cursor.getColumnIndex(DB_alarm.COL_TITRE ));
		 						String start_timestamp = Cursor.getString(Cursor.getColumnIndex(DB_alarm.COL_START_TIME ));
		 						String end_timestamp = Cursor.getString(Cursor.getColumnIndex(DB_alarm.COL_END_TIME ));
		 						String phone = Cursor.getString(Cursor.getColumnIndex(DB_alarm.COL_PHONE ));
		 						String notes = Cursor.getString(Cursor.getColumnIndex(DB_alarm.COL_NOTES ));
		 						
		 						Date date_start = new Date(Long.parseLong(start_timestamp));
		 						Date date_end = new Date(Long.parseLong(end_timestamp));
		
		 						// pour affichage de la plage horaire
		 						Calendar cal = Calendar.getInstance();
		 						cal.setTime(date_start);
		 						String year_start = String.valueOf(cal.get(Calendar.YEAR));
		 						String month_start = String.valueOf(cal.get(Calendar.MONTH));
		 						String day_start = String.valueOf(cal.get(Calendar.DAY_OF_MONTH));
		 						String hour_start = String.valueOf(cal.get(Calendar.HOUR_OF_DAY));
		 						String minute_start = String.valueOf(cal.get(Calendar.MINUTE));
		 						
		 						cal.setTime(date_end);
		 						String year_end = String.valueOf(cal.get(Calendar.YEAR));
		 						String month_end = String.valueOf(cal.get(Calendar.MONTH));
		 						String day_end = String.valueOf(cal.get(Calendar.DAY_OF_MONTH));
		 						String hour_end = String.valueOf(cal.get(Calendar.HOUR_OF_DAY));
		 						String minute_end = String.valueOf(cal.get(Calendar.MINUTE));
		 						
		 						if( minute_start.equals("0") || minute_start.equals("5")   )
		 						{
		 							minute_start = "0" + minute_start; 
		 						}
		 						
		 						if( minute_end.equals("0") || minute_end.equals("5")   )
		 						{
		 							minute_end = "0" + minute_end;
		 						}
		 						
		 						String infos = hour_start + ":" + minute_start + " à " + hour_end + ":" + minute_end; 
		 						
		 						// 0 * 50 = 0  puis  0 * 50 + 50 = 50  
		 						// 2 * 50 = 100 puis 2* 50 + 50 = 150
		 						// 4 * 50 = 200 puis 4 * 50 + 50 = 250							
		 						
		 						int elem1 = cpt * 50;
		 						int elem2 = elem1 + 50;
		 						cpt = cpt + 2;
		 						
		 						//appointment_liste.add(new appointment(index, titre, date_start, date_end, phone, notes));
		 						
		 						int id = Integer.valueOf(sid);
		 						appointment_liste.add(new appointment(id, titre, date_start, date_end, phone, notes));
		 						
		 						//appointment pipo = new appointment();
		 						//pipo = appointment_liste.get(0);
		 						
		 				        //display_appointment(date_start, date_end, titre , "#3F51B5", index, infos, elem1, elem2);
		 				        display_appointment(date_start, date_end, titre , "#3F51B5", id, infos, elem1, elem2);
		 				        
		 				        index = index + 1;
	 						
	 					} while (Cursor.moveToNext());
	 					
 				}
 		}
		
    	else
		{
			flag = false;
			store_nb_appointment = 0;
		}
	

    }
    
    private void previousCalendarDate()
    {
    	if(flag == true)
    	{	
    		//mLayout.removeViewAt(eventIndex - 1);
    		int cpt = 0;
    		for(int i = 0; i < store_nb_appointment; i++)
    		{
    			int elem1 = cpt * 50;
				int elem2 = elem1 + 50;
				cpt = cpt + 2;
				
				// 0 * 50 = 0  puis  0 * 50 + 50 = 50  
					// 2 * 50 = 100 puis 2* 50 + 50 = 150
					// 4 * 50 = 200 puis 4 * 50 + 50 = 250				
    			
    			  View namebar = mLayout.findViewById(elem1);
    		      ViewGroup parent = (ViewGroup) namebar.getParent();
    		      if (parent != null) 
    		      {
    		         parent.removeView(namebar);
    		     }
    		     
    		      namebar = mLayout.findViewById(elem2);
    		      parent = (ViewGroup) namebar.getParent();
    		      if (parent != null) 
    		      {
    		         parent.removeView(namebar);
    		     }

    		}
    		
    		
    		
    	} 
    	cal_display.add(Calendar.DAY_OF_MONTH, -1);
        DisplayDate.setText(displayDateInString(cal_display.getTime()));
        long timestamp = cal_display.getTimeInMillis();

        
    	//Toast.makeText(getApplicationContext(), "Prev", Toast.LENGTH_SHORT).show();

        
        gestion_appointment(timestamp);
        //displayDailyEvents();
    }
    
    private void nextCalendarDate()
    {
    	
    	//1485281300114
    	//1485212400
    	
    	if(flag == true)
    	{	
    		//mLayout.removeViewAt(eventIndex - 1);
    		
    		//int[] id_table = {100, 150, 200, 250, 300, 350 , 400 , 450, 500, 550 , 650 , 700 , 750 , 800 , 850, 900 , 950 , 1000 };
    		//store_nb_appointment; 
    		int cpt = 0;
    		for(int i = 0; i < store_nb_appointment; i++)
    		{
    			int elem1 = cpt * 50;
				int elem2 = elem1 + 50;
				cpt = cpt + 2;
				
				// 0 * 50 = 0  puis  0 * 50 + 50 = 50  
					// 2 * 50 = 100 puis 2* 50 + 50 = 150
					// 4 * 50 = 200 puis 4 * 50 + 50 = 250				
    			
    			  View namebar = mLayout.findViewById(elem1);
    		      ViewGroup parent = (ViewGroup) namebar.getParent();
    		      if (parent != null) 
    		      {
    		         parent.removeView(namebar);
    		     }
    		     
    		      namebar = mLayout.findViewById(elem2);
    		      parent = (ViewGroup) namebar.getParent();
    		      if (parent != null) 
    		      {
    		         parent.removeView(namebar);
    		     }

    		}
    		
    	} 

        
        
        // 1485817200 pour le 31 janvier 2017
        // 1485903600 le 1 fevrier 2017
    	
        long tt = cal_display.getTimeInMillis();

        
    	cal_display.add(Calendar.DAY_OF_MONTH, 1);
        DisplayDate.setText(displayDateInString(cal_display.getTime()));
        long timestamp = cal_display.getTimeInMillis();
        
        //Toast.makeText(getApplicationContext(), "Next", Toast.LENGTH_SHORT).show();

        
        gestion_appointment(timestamp);
        //displayDailyEvents();
    }
    
    private String displayDateInString(Date mDate)
    {
        SimpleDateFormat formatter = new SimpleDateFormat("d MMMM, yyyy", Locale.ENGLISH);
        return formatter.format(mDate);
    }
    
    
    private void display_appointment(Date start, Date end, String message, String color, final int index, String info, int elem1, int elem2)
    {
    	 SimpleDateFormat timeFormatter = new SimpleDateFormat("HH:mm", Locale.ENGLISH);
    	 
    	 /*int count = mLayout.getChildCount();

    	    for (int i = 0; i < count; i++)
    	    {

    	        View view = mLayout.getChildAt(i);

    	        mLayout.removeView(view);

    	    }
    	 */
      	
     	// mLayout.removeView(mEventView);
     	// mLayout.removeView(tv);
    	 
     	
     //	RelativeLayout formLayout = (RelativeLayout)findViewById(R.id.left_event_column);
     //	formLayout.removeAllViews();
     	
     	 
    	 
    	 int height = getEventTimeFrame(start, end);
	       
	     String displayValue = timeFormatter.format(start);
	     String[]hourMinutes = displayValue.split(":");
	     int hours = Integer.parseInt(hourMinutes[0]);
	     int minutes = Integer.parseInt(hourMinutes[1]);
	     int topViewMargin = (hours * 60) +  minutes; //     ((minutes * 60) / 100);
	     //TextView mEventView = new TextView(agenda02.this);
	     mEventView = new TextView(agenda02.this);
	     
	     //mEventView.setId(100);
	        
	     RelativeLayout.LayoutParams lParam = new RelativeLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
	     lParam.addRule(RelativeLayout.ALIGN_PARENT_TOP);
	     lParam.topMargin = topViewMargin * 2;
	     lParam.leftMargin = 24;
	     mEventView.setLayoutParams(lParam);
	     mEventView.setPadding(24, 0, 24, 0);
	     mEventView.setPadding(120, 0, 120, 0);
	        
	     mEventView.setHeight(height * 2);
	     mEventView.setGravity(0x11);
	     mEventView.setTextColor(Color.parseColor("#ffffff"));
	  
	     mEventView.setText(message);
	     mEventView.setBackgroundColor(Color.parseColor(color));
	      
	     mEventView.setId(elem1);
	     
	     
	      TextView ddffeditText = (TextView) findViewById(451);
	      
	      View myView = findViewById(451);
	      
	     
	     mLayout.addView(mEventView, eventIndex - 1);
	     
	    
	     tv = new TextView(this);
	     tv.setX(20);
	     tv.setX(20);
	     tv.setText(info);
	     tv.setTextColor(Color.parseColor("#ffffff"));
	     tv.setLayoutParams(lParam);
	     tv.setId(elem2);
	     
	     mLayout.addView(tv);
	     
	     /* OK */
	     //View namebar = mLayout.findViewById(555);
	     //ViewGroup parent = (ViewGroup) namebar.getParent();
	     //if (parent != null) {
	     //    parent.removeView(namebar);
	     //}
	     
	     
	     /* OK pour le n -1 */ 
	     //int total = mLayout.getChildCount();
	     //View childView = mLayout.getChildAt(total-1);
	     //int pos = childView.getId();
	     //View namebar = mLayout.findViewById(pos);
	     //ViewGroup parent = (ViewGroup) namebar.getParent();
	     //if (parent != null) {
	     //    parent.removeView(namebar);
	     //}
	     //total = mLayout.getChildCount();
	     
	     
	     //final int index = index;
	     mEventView.setOnClickListener(new OnClickListener() 
		 {
				public void onClick(View v)
				{
	               Log.i("TAG", "index :" + index);
	               //Toast.makeText(getApplicationContext(), "---->Clicked Button Index :" + index, Toast.LENGTH_LONG).show();
	               Intent intent = new Intent(agenda02.this, infos_appointment.class);
	               intent.putExtra("index", index);
	               intent.putExtra("date_selection", date_selection);
	               startActivity(intent);
				}
		 });
    	
    }
    
    
    private int getEventTimeFrame(Date start, Date end)
    {
        long timeDifference = end.getTime() - start.getTime();
        Calendar mCal = Calendar.getInstance();
        mCal.setTimeInMillis(timeDifference);
        
        long tmp = timeDifference / 60000;
        int nbre_minutes = (int) tmp;
        return nbre_minutes;
        
        //int hours = mCal.get(Calendar.HOUR);
        //int minutes = mCal.get(Calendar.MINUTE);
        //return (hours * 60) + ((minutes * 60) / 100);
    }
    
    
    
}