package mercuryretrograde.findyourfate.com;
 
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale; 

import android.app.Activity;
import android.content.Context; 
import android.content.SharedPreferences;
import android.database.Cursor; 
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.Typeface;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class calendaradapter extends BaseAdapter {
	
   private static SQLiteDatabase DB;   
	private Context mContext;
	private java.util.Calendar month;
	public GregorianCalendar pmonth; 
	public GregorianCalendar pmonthmaxset;
	private GregorianCalendar selectedDate;
	int firstDay;
	int maxWeeknumber;
	int maxP;
	int calMaxP;
	int lastWeekDay;
	int leftDays;
	int mnthlength;
	int m;
	int y;
	String itemvalue, curentDateString;
	DateFormat df;
	private ArrayList<String> items;
	public static List<String> dayString;
	private View previousView;
	public static final String MyPREFERENCES = "MyPrefs" ;
    public static final String name = "fontsize";  
    public static SharedPreferences sharedpreferences;  
    private static Typeface mTypeface;
    int ssize,fsize;
	
	public calendaradapter(Context c, GregorianCalendar monthCalendar) {
		calendaradapter.dayString = new ArrayList<String>(); 
		Locale.setDefault( Locale.US );
		month = monthCalendar;
		selectedDate = (GregorianCalendar) monthCalendar.clone();
		mContext = c;
		month.set(GregorianCalendar.DAY_OF_MONTH, 1);
		this.items = new ArrayList<String>();
		df = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
		curentDateString = df.format(selectedDate.getTime());
		 
			 
	 	 
  
		refreshDays();
	}

	public void setItems(ArrayList<String> items) {
		for (int i = 0; i != items.size(); i++) {
			if (items.get(i).length() == 1) {
				items.set(i, "0" + items.get(i));
			}
		}
		this.items = items;
	}

	public int getCount() {
		return dayString.size();
	}

	public Object getItem(int position) {
		return dayString.get(position);
	}

	public long getItemId(int position) {
		return 0;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		View v = convertView;
		TextView dayView;
		
		if (convertView == null)
		{ 
			LayoutInflater vi = (LayoutInflater) mContext .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			v = vi.inflate(R.layout.calendar_item, null);
		}
		
		mTypeface = Typeface.createFromAsset(mContext.getAssets(), "arial.ttf"); 
        DisplayMetrics metrics = new DisplayMetrics(); 
        Activity activity = (Activity) mContext;;
        activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
         

        if (metrics.densityDpi <= DisplayMetrics.DENSITY_LOW) {
        	//Toast.makeText(this, "low screen",Toast.LENGTH_LONG).show();
        	ssize=13;
        	 
        } else if (metrics.densityDpi <= DisplayMetrics.DENSITY_HIGH) {
        	// Toast.makeText(this, "high screen",Toast.LENGTH_LONG).show();
        	ssize=17;
        	 
        }
        else if (metrics.densityDpi <= DisplayMetrics.DENSITY_MEDIUM) {
        	// Toast.makeText(this, "medium screen",Toast.LENGTH_LONG).show();
        	ssize=20;
        	 
        }
        else if (metrics.densityDpi <= DisplayMetrics.DENSITY_XHIGH) {
        	 //Toast.makeText(this, "xLarge screen",Toast.LENGTH_LONG).show();
        	ssize=23;
        	 
        }
        else if (metrics.densityDpi <= DisplayMetrics.DENSITY_XXHIGH) {
        	// Toast.makeText(this, "xxLarge screen",Toast.LENGTH_LONG).show();
        	ssize=25;
        	 
        }
        else if (metrics.densityDpi <= DisplayMetrics.DENSITY_XXXHIGH) {
        	 
        	ssize=28;
        	 
        }
        else {
        	 
        	ssize=17;
        	 
        }
        
        String fontkey=getfontName();  
        if (fontkey != null) 
        {
       	  if(fontkey.equals("Small"))
       	  {
       		  fsize=13;
       	  }
       	  else if(fontkey.equals("Medium"))
       	  {
       		  fsize=17;
       	  }
       	  else if(fontkey.equals("Large"))
       	  {
       		  fsize=21;
       	  }
       	if(fontkey.equals("Larger"))
       	  {
       		  fsize=25;
       	  }
    	if(fontkey.equals("X-Large"))
       	  {
       		  fsize=28;
       	  }
        }
        else
        {
   	   fsize=ssize;  
        }
		dayView = (TextView) v.findViewById(R.id.date);
		dayView.setTextSize(fsize); 
		dayView.setTypeface(mTypeface);
		String[] separatedTime = dayString.get(position).split("-");
		String gridvalue = separatedTime[2].replaceFirst("^0*", "");
		 if ((Integer.parseInt(gridvalue) > 1) && (position < firstDay)) {
			 
			 dayView.setText("");
		 v.setBackgroundColor(Color.parseColor("#dedfe7"));
			//dayView.setTextColor(Color.parseColor("#dedfe7"));
			//dayView.setClickable(false);
			//dayView.setFocusable(false);
		} else if ((Integer.parseInt(gridvalue) < 7) && (position > 28)) {
			dayView.setText("");
			 v.setBackgroundColor(Color.parseColor("#dedfe7"));
		  // dayView.setTextColor(Color.parseColor("#dedfe7"));
			//dayView.setClickable(false);
			//dayView.setFocusable(false);
		} else {
		     
			
			
			dayView.setTextColor(Color.BLACK);
			dayView.setText(gridvalue);
		  
			v.setBackgroundColor(Color.parseColor("#dedfe7"));
		
		
		// create date string for comparison
		String date = dayString.get(position);  
		
				if (date.length() == 1) {
					date ="0"+date;
				}
				String monthStr = ""+(month.get(GregorianCalendar.MONTH) + 1);
				if (monthStr.length() == 1) {
					monthStr ="0"+monthStr;
				}
		String tday=date.replaceAll("-", ""); 
		 DB = new DatabaseHandler(mContext).getReadableDatabase();
	  //  Cursor cursor = mDataBase.rawQuery("SELECT * FROM mercury WHERE date2>='"+tday+"' AND date1<='"+tday+"' and station='SR'  order by sno asc", null);
		
		//Cursor cursor = DB.rawQuery("SELECT * FROM findmercury WHERE date2>='"+tday+"' AND date1<'"+tday+"'  order by sno asc", null);
		
		  Cursor cursor = DB.rawQuery("SELECT * FROM mercury WHERE date2>='"+tday+"' AND date1<='"+tday+"' order by sno asc", null);   
		 	  
			
		  String  station="";
		   
	    try { 
	             
	    	cursor.moveToFirst();
	    	while (!cursor.isAfterLast()) {
	    	   
	    	     
	    	//while (cursor.moveToNext()) {
	    	  
	    	  //Toast msg = Toast.makeText(mContext, "today"+tday, Toast.LENGTH_LONG);
	  		 //msg.show();
	    	  
	    		 station=""; 
	    	  station= cursor.getString(4);
	    	  int sno= cursor.getInt(0);
	    	  
	    	 
	    	  if(station.equals("SG"))
	    	  {
	    		   Log.e("sg = ",""+tday);  
			    	Log.e("sgstation = ",""+station);
	    	 	v.setBackgroundColor(Color.GREEN);
	    	  }
	    	  else if(station.equals("SR"))
	            {
	    		 Log.e("tday = ",""+tday);  
		    	 Log.e("station = ",""+station);
		    	//Log.e("sno = ",""+sno);
	    		  v.setBackgroundColor(Color.RED);
	    		  
  	             } 
	    	  
	    	  
	    	  else if(station.equals("SD"))
	    	  {
	    	    	 Log.e("sdday = ",""+tday);  
			    	 Log.e("sdstation = ",""+station);
	    	 	  v.setBackgroundColor(Color.YELLOW);
	    	  }
	    	 
	    	  else
	    	  {
	    		  station="";
	    			 v.setBackgroundColor(Color.parseColor("#dedfe7"));
	    	  }
	    	 
	    	   
	    	   cursor.moveToNext();
	    	   
	 		      }	 
	    	
	    	// dayView.setText("");
	    	// v.setBackgroundColor(Color.parseColor("#dedfe7"));
	 		      cursor.close(); 
	 		     // } 
	    }
	    finally {
	    	 // v.setBackgroundColor(Color.parseColor("#dedfe7"));
	        cursor.close();
	    }
	    DB.close();
		    
		 
		// show icon if date is not empty and it exists in the items array
		/*ImageView iw = (ImageView) v.findViewById(R.id.date_icon);
		if (date.length() > 0 && items != null && items.contains(date)) {
			iw.setVisibility(View.VISIBLE);
		} else {
			iw.setVisibility(View.INVISIBLE);
		}*/
		}
		return v;
	}
	 
	public View setSelected(View view) {
		 if (previousView != null) {
			previousView.setBackgroundResource(R.drawable.list_item_background);
		}
		previousView = view;
		//view.setBackgroundResource(R.drawable.calendar_cel_selectl);
		return view; 
	}

	protected String getfontName()
	{
		 
		 String restoredText=null;
		 sharedpreferences=mContext.getSharedPreferences(MyPREFERENCES,Context.MODE_PRIVATE);
	      if (sharedpreferences.contains(name))
	      {
	    	  restoredText = sharedpreferences.getString("fontsize", name); 
	       
	    	 
	      
	      }


	return restoredText;
	}
	
	public void refreshDays() {
		// clear items
		items.clear();
		dayString.clear();
		Locale.setDefault( Locale.US );
		pmonth = (GregorianCalendar) month.clone();
		// month start day. ie; sun, mon, etc
		firstDay = month.get(GregorianCalendar.DAY_OF_WEEK);
		
		maxWeeknumber = month.getActualMaximum(GregorianCalendar.WEEK_OF_MONTH);
		
		
		//maxWeeknumber = month.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
		mnthlength = maxWeeknumber * 7;
		
		//mnthlength = maxWeeknumber+firstDay ;
		Log.e("mnthlength = ",""+mnthlength);
		
		 maxP = getMaxP();  
		Log.e("maxP = ",""+maxP);
		 calMaxP = maxP - (firstDay - 1);// calendar offday starting 24,25 ...
		
		pmonthmaxset = (GregorianCalendar)pmonth.clone();
		
		//Log.e("pmonthmaxset = ",""+pmonthmaxset);
	  pmonthmaxset.set(GregorianCalendar.DAY_OF_MONTH, calMaxP + 1);
	    
	  
		 
			for (int n=firstDay; n < mnthlength+firstDay; n++) { 
			itemvalue = df.format(pmonthmaxset.getTime());
			pmonthmaxset.add(GregorianCalendar.DATE, 1);
			dayString.add(itemvalue);  
			 
		}
	}

	
	 
	 

	private int getMaxP() {
		int maxP;
		if (month.get(GregorianCalendar.MONTH) == month
				.getActualMinimum(GregorianCalendar.MONTH)) {
			pmonth.set((month.get(GregorianCalendar.YEAR) - 1),
					month.getActualMaximum(GregorianCalendar.MONTH), 1);
		} else {
			pmonth.set(GregorianCalendar.MONTH,
					month.get(GregorianCalendar.MONTH) - 1);
		}
		maxP = pmonth.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);

		return maxP;
	}

}
