package com.androidbegin.buttonclicktutorial;

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.View;
import android.view.View.OnClickListener;
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 agenda03 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;
	
	final static ArrayList<appointment> appointment = new ArrayList<appointment>();
	
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
		        super.onCreate(savedInstanceState);
		        setContentView(R.layout.agenda_view);
		        db = new DB_alarm(getApplicationContext());
		        
		        getActionBar().setDisplayHomeAsUpEnabled(true);
		        
		        //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();
				String 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);
		        long 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();
		            }
		        });
    }
    
    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();
 		
    		if(val != 0)
    		{
        		//eventIndex = mLayout.getChildCount();
        		flag = true;
    			
 				if (Cursor.moveToFirst()) 
 				{
	 					do 
	 					{
		 						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 ));
		 						
		 						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));
		 						
		 						
		 						appointment.add(new appointment(1, titre, date_start, date_start, "phone", "notes"));
		 						
		 						String infos = hour_start + ":" + minute_start + " à " + hour_end + ":" + minute_end; 
		 				        display_appointment(date_start, date_end, titre , "#3F51B5", 123, infos);
	 						
	 					} while (Cursor.moveToNext());
	 					
 				}
 		}
		
    	else
		{
			flag = false;
		}
	

    }
    
    private void previousCalendarDate()
    {
    	if(flag == true)
    	{	
    		//mLayout.removeViewAt(eventIndex - 1);
    		//mLayout.removeViewAt(0);
    		//mLayout.removeViewAt(1);
    		mLayout.removeViewAt(25); // 0
    		mLayout.removeViewAt(26); // 1
    	} 
    	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 zorro = mLayout.getChildCount();
    		mLayout.removeViewAt(25); // 0
    		//mLayout.removeViewAt(26); // 1

    	} 

        
        
        // 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, int indexxx, String info)
    {
    	 SimpleDateFormat timeFormatter = new SimpleDateFormat("HH:mm", Locale.ENGLISH);
      	
    	 eventIndex = mLayout.getChildCount();
    	 
     	// 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(agenda03.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(12345);   
	     
	     
	     mLayout.addView(mEventView, eventIndex - 1);
	     //mLayout.addView(mEventView);
	    
	     tv = new TextView(this);
	     tv.setX(20);
	     tv.setX(20);
	     tv.setText(info);
	     tv.setTextColor(Color.parseColor("#ffffff"));
	     tv.setLayoutParams(lParam);
	     tv.setId(55555);   

	    
	     //mLayout.addView(tv);
	     mLayout.addView(tv, eventIndex - 1);
	     
	     
// int plouf = tv.getId();
	     
 	     
// mLayout.removeViewAt(plouf); // 0
	    
	     //(EditText)linearLayout.findViewById(yourEditText.getId()); 
		  // TextView editText = (TextView) findViewById(R.id.55555); 
	     
 		eventIndex = mLayout.getChildCount();

	     
	     final int index = indexxx;
	     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 myIntent = new Intent(agenda03.this, infos_appointment.class);
	               /*
	               Intent intent = new Intent(MainActivity.this, debug02.class); //Contact_details 
					intent.putExtra("id", position);
					intent.putExtra("nom", nom);
					intent.putExtra("prenom", prenom);
					intent.putExtra("adresse", adresse);
					intent.putExtra("email", email);
					intent.putExtra("portable", portable);
					intent.putExtra("fixe", fixe);
					intent.putExtra("photograph", photograph);
					startActivity(intent);
	               */
	               
	               
				   startActivity(myIntent);
				}
		 });
    	
    }
    
    
    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);
    }
    
    
    
}