package mercuryretrograde.findyourfate.com;

import java.text.DateFormat;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.Locale; 

import android.annotation.SuppressLint; 
import android.app.Activity; 
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent; 
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor; 
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;  
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu; 
import android.view.MenuItem;
import android.view.View; 
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.GridView; 
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast; 

public class calendar extends Activity {	 
	public GregorianCalendar month, itemmonth;// calendar instances.
	public calendaradapter adapter;// adapter instance
	public Handler handler;// for grabbing some event values for showing the dot							// marker.
	public ArrayList<String> items; // container to store calendar items which
	 
	
		public static final String MyPREFERENCES = "MyPrefs" ;
	    public static final String name = "fontsize";  
	    public static SharedPreferences sharedpreferences;
	    private static Typeface mTypeface;
	    final Context context = this;
	    int fsize,ssize;
	    
	 @SuppressLint("NewApi")
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState); 
	     setContentView(R.layout.calendar);

	          
	        DisplayMetrics metrics = new DisplayMetrics(); 
	        Activity activity = (Activity) context;
	        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=20;
	        	 
	        }
	        else if (metrics.densityDpi <= DisplayMetrics.DENSITY_MEDIUM) {
	        	// Toast.makeText(this, "medium screen",Toast.LENGTH_LONG).show();
	        	ssize=17;
	        	 
	        }
	        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;  
	        }
		 Locale.setDefault( Locale.US ); 
		month = (GregorianCalendar) GregorianCalendar.getInstance();
		itemmonth = (GregorianCalendar) month.clone();
		items = new ArrayList<String>();
		adapter = new calendaradapter(this, month);
		GridView gridview = (GridView) findViewById(R.id.gridview);
		gridview.setAdapter(adapter); 
		handler = new Handler();
		handler.post(calendarUpdater);
		mTypeface = Typeface.createFromAsset(calendar.this.getAssets(), "arial.ttf"); 
		TextView title = (TextView) findViewById(R.id.title);
		TextView tabtitle = (TextView) findViewById(R.id.tabtitle);
		TextView mrlabel = (TextView) findViewById(R.id.mrlabel);
		TextView mdlabel = (TextView) findViewById(R.id.mdlabel);
		mrlabel.setTextSize(fsize); 
		mrlabel.setTypeface(mTypeface,Typeface.BOLD_ITALIC);
		mdlabel.setTextSize(fsize); 
		mdlabel.setTypeface(mTypeface,Typeface.BOLD_ITALIC);
		tabtitle.setTextSize(fsize); 
		tabtitle.setTypeface(mTypeface,Typeface.BOLD_ITALIC);
		title.setTextSize(fsize); 
		title.setTypeface(mTypeface,Typeface.BOLD_ITALIC);
		title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));
		RelativeLayout previous = (RelativeLayout) findViewById(R.id.previous);
		previous.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				setPreviousMonth();
				refreshCalendar();
			}
		});

		RelativeLayout next = (RelativeLayout) findViewById(R.id.next);
		next.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				setNextMonth();
				refreshCalendar();

			}
		});

		 
	}

	protected void setNextMonth() {
		if (month.get(GregorianCalendar.MONTH) == month
				.getActualMaximum(GregorianCalendar.MONTH)) {
			month.set((month.get(GregorianCalendar.YEAR) + 1),
					month.getActualMinimum(GregorianCalendar.MONTH), 1);
		} else {
			month.set(GregorianCalendar.MONTH,
					month.get(GregorianCalendar.MONTH) + 1);
		}

	}

	protected void setPreviousMonth() {
		if (month.get(GregorianCalendar.MONTH) == month
				.getActualMinimum(GregorianCalendar.MONTH)) {
			month.set((month.get(GregorianCalendar.YEAR) - 1),
					month.getActualMaximum(GregorianCalendar.MONTH), 1);
		} else {
			month.set(GregorianCalendar.MONTH,
					month.get(GregorianCalendar.MONTH) - 1);
		}

	}

	protected void showToast(String string) {
		Toast.makeText(this, string, Toast.LENGTH_SHORT).show();

	}

	public void refreshCalendar() {
		TextView title = (TextView) findViewById(R.id.title);
		title.setTextSize(fsize); 
		title.setTypeface(mTypeface,Typeface.BOLD_ITALIC);
		adapter.refreshDays();
		adapter.notifyDataSetChanged();
		handler.post(calendarUpdater); // generate some calendar items
		title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));
	}

	public Runnable calendarUpdater = new Runnable() {

		@Override
		public void run() {
			items.clear();
			// Print dates of the current week
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd",Locale.US);
			@SuppressWarnings("unused")
			String itemvalue=null;
			for (int i = 0; i < 7; i++) {
				itemvalue = df.format(itemmonth.getTime());
				itemmonth.add(GregorianCalendar.DATE, 1);
				items.add("2012-09-12");
				items.add("2012-10-07");
				items.add("2012-10-15");
				items.add("2012-10-20");
				items.add("2012-11-30");
				items.add("2012-11-28");
				}
			adapter.setItems(items);
			adapter.notifyDataSetChanged();
		}
	};
 
 
@Override
public void onStart() {
    super.onStart();
    
}

@Override
public void onStop() {
    super.onStop();
   
}
/*
@Override
     public void onBackPressed() {
         AlertDialog.Builder builder = new AlertDialog.Builder(this);
         builder.setMessage("Are you sure you want to leave this App.")
                .setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                    	Intent int_home1 = new Intent(calendar.this, MercuryRetrogradeActivity.class);
            int_home1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(int_home1);
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                         dialog.cancel();
                    }
                });
         AlertDialog alert = builder.create();
         alert.setIcon(R.drawable.alert);
         alert.show();

     }*/
     
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
	getMenuInflater().inflate(R.menu.main_menu, menu);
   // MenuItem item = menu.findItem(R.id.cfont);
   //	item.setVisible(false);
   return true; 
} 

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


return restoredText;
}

 

@SuppressLint("NewApi")
@Override
public boolean onOptionsItemSelected(MenuItem item) {
	if(item.getItemId()== android.R.id.home)
	 {
           Intent int_home = new Intent(this, MercuryRetrogradeActivity.class);
           int_home.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
           startActivity(int_home);
	 }
	 else if(item.getItemId()== R.id.icon_abt)
    {	 
	            Intent int_abt = new Intent(this, contentmercury.class);
	            int_abt.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	            startActivity(int_abt);
	 }
	 else if(item.getItemId()==R.id.icon_find)
	 {	 
	 Intent int_tday = new Intent(this, todaymercury.class);
	        int_tday.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	        startActivity(int_tday);
	 }
	 else if(item.getItemId()==R.id.icon_tday)
	 {
		            Intent int_cal = new Intent(this, calendar.class);
		            int_cal.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		            startActivity(int_cal);
	 }       
	 else if(item.getItemId()==R.id.icon_sign)
	 {
		            Intent int_sign = new Intent(this, zodiacsign.class);
		            int_sign.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		            startActivity(int_sign);
	 }
	
	
	 else if (item.getItemId() == R.id.cfont) { 
			initiatePopupWindow();
		}
	 else if(item.getItemId()==R.id.icon_exit)
	 {
		 AlertDialog.Builder builder = new AlertDialog.Builder(this);
         builder.setMessage("Are you sure you want to leave this App.")
                .setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                    	Intent intent = new Intent(Intent.ACTION_MAIN);
        		    	intent.addCategory(Intent.CATEGORY_HOME);
        		    	intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        		    	startActivity(intent);
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                         dialog.cancel();
                    }
                });
         AlertDialog alert = builder.create();
         alert.setTitle("Close App.");
         alert.setIcon(R.drawable.alert);
         alert.show();
	 }
	 else if(item.getItemId()==R.id.icon_set)
	 {
	        	  Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
	        	 emailIntent.setType("text/plain");
	        	 emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Mercury Retrograde - findyourfate.com");
	        	 emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Hi,I would like to suggest, this Mercury Retrograde App to you.Click this link to download App http://goo.gl/5IZD3z"+"\n\n"+" Regards");
	     	     startActivity(Intent.createChooser(emailIntent, "Share via")); 
	 }
	 else
	 {
	 }
	        	 
	            return true;
    }
 

public static int get(int year) {
	// TODO Auto-generated method stub
	return 0;
}

private void initiatePopupWindow() {
		
	 LayoutInflater layoutInflater 
     = (LayoutInflater)getBaseContext()
      .getSystemService(LAYOUT_INFLATER_SERVICE);  
    final View popupView = layoutInflater.inflate(R.layout.fontchange, null);  
             final PopupWindow popupWindow = new PopupWindow(
               popupView, 
               LayoutParams.WRAP_CONTENT,  
                     LayoutParams.WRAP_CONTENT);  
           
             Button btnDismiss = (Button)popupView.findViewById(R.id.btncancel);
           final RadioGroup radioSexGroup = (RadioGroup)popupView.findViewById(R.id.rgOpinion);
         Button btnDisplay = (Button)popupView.findViewById(R.id.btnDisplay); 
     	RadioButton s = (RadioButton)popupView.findViewById(R.id.small);
     	RadioButton m= (RadioButton)popupView.findViewById(R.id.normal);
     	RadioButton l= (RadioButton)popupView.findViewById(R.id.large);
     	RadioButton ll= (RadioButton)popupView.findViewById(R.id.larger);
     	RadioButton xl= (RadioButton)popupView.findViewById(R.id.xlarge);
     	sharedpreferences=getSharedPreferences(MyPREFERENCES,Context.MODE_PRIVATE);
	      if (sharedpreferences.contains(name))
	      {
	       String fontsize=sharedpreferences.getString("fontsize", name);
	        if(fontsize.equals("Small"))
	        {
	        	s.setChecked(true);
	        }
	        else if(fontsize.equals("Medium"))
	        {
	        	m.setChecked(true);
	        }
	        else if(fontsize.equals("Large"))
	        {
	        	l.setChecked(true);
	        }
	        else if(fontsize.equals("Larger"))
	        {
	        	ll.setChecked(true);
	        }
	        else if(fontsize.equals("X-Large"))
	        {
	        	xl.setChecked(true);
	        }
	    	  
	        else
	        {
	        	m.setChecked(true);
	        }
	      } 

             btnDismiss.setOnClickListener(new Button.OnClickListener(){

     @Override
     public void onClick(View v) {
      // TODO Auto-generated method stub
      popupWindow.dismiss();
     }});
             
           btnDisplay.setOnClickListener(new OnClickListener() {
		    	  
		  		@Override
		  		public void onClick(View v) {
		  			 
		  			 
		  			int selectedId = radioSexGroup.getCheckedRadioButtonId();  
		  			RadioButton radioSexButton = (RadioButton)popupView.findViewById(selectedId);
		   String fontsize=radioSexButton.getText().toString();
		  			//Toast.makeText(fontchange.this,"vv"+fontsize, Toast.LENGTH_SHORT).show();
		  			
		   Editor editor = sharedpreferences.edit(); 
		  			 editor.putString(name, fontsize); 
		  		      editor.commit();
		  		    popupWindow.dismiss();
		  		  Intent icon_home1 = new Intent(calendar.this, calendar.class);
			    	icon_home1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		            startActivity(icon_home1);
		  			 
		  		}
		   
		  	});
               
           popupWindow.showAtLocation(popupView, Gravity.CENTER, 0, 0);
             popupWindow.showAsDropDown(popupView, 50, -30);
}
}