package mercuryretrograde.findyourfate.com;  
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
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.database.Cursor;
import android.database.sqlite.SQLiteDatabase; 
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;  
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.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup; 
import android.widget.TextView;
@SuppressLint("NewApi")
public class todaymercury extends Activity {
    /** Called when the activity is first created. */
	   int fsize,ssize;
	    final Context context = this;   
	    protected SQLiteDatabase DB;
		 protected Cursor cursor; 
	    public static final String name = "fontsize";  
	    public static SharedPreferences sharedpreferences;
		public static final String MyPREFERENCES = "MyPrefs" ;
		private QuickAction quick;
		ImageView Share;
		 WebView content;  
		 String signtext=null;
		 String medate=null;
		public void onCreate(Bundle savedInstanceState) {
	    	StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork() .penaltyLog().build()); 
	  super.onCreate(savedInstanceState); 
	  setContentView(R.layout.sharelayout);
	   content=(WebView) findViewById(R.id.content);
       String result = null;
        DisplayMetrics metrics = new DisplayMetrics(); 
	        Activity activity = (Activity) context;
	        activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
	         
	        content.getSettings().setSupportZoom(true); 
            content.getSettings().setBuiltInZoomControls(true);

	         
	 		 String userAgent = new WebView(todaymercury.this).getSettings().getUserAgentString();
		        if (userAgent.contains("Mobile")) {
		       
	        if (metrics.densityDpi <= DisplayMetrics.DENSITY_LOW) {
	        	//Toast.makeText(this, "low screen",Toast.LENGTH_LONG).show();
	        	ssize=1;
	        	 
	        } else if (metrics.densityDpi <= DisplayMetrics.DENSITY_HIGH) {
	        	// Toast.makeText(this, "high screen",Toast.LENGTH_LONG).show();
	        	ssize=2;
	        	 
	        }
	        else if (metrics.densityDpi <= DisplayMetrics.DENSITY_MEDIUM) {
	        	// Toast.makeText(this, "medium screen",Toast.LENGTH_LONG).show();
	        	ssize=2;
	        	 
	        }
	        else if (metrics.densityDpi <= DisplayMetrics.DENSITY_XHIGH) {
	        	 //Toast.makeText(this, "xLarge screen",Toast.LENGTH_LONG).show();
	        	ssize=3;
	        	 
	        }
	        else if (metrics.densityDpi <= DisplayMetrics.DENSITY_XXHIGH) {
	        	// Toast.makeText(this, "xxLarge screen",Toast.LENGTH_LONG).show();
	        	ssize=4;
	        	 
	        }
	        else if (metrics.densityDpi <= DisplayMetrics.DENSITY_XXXHIGH) {
	        	 
	        	ssize=6;
	        	 
	        }
	        else {
	        	 
	        	ssize=3;
	        	 
	        }
		        }
		        else
		        {
		        	ssize=3;
		        }
		        String fontkey=getfontName(); 
		       
		        if (fontkey != null) 
		        {
		       	  if(fontkey.equals("Small"))
		       	  {
		       		  fsize=1;
		       	  }
		       	  else if(fontkey.equals("Medium"))
		       	  {
		       		  fsize=2;
		       	  }
		       	  else if(fontkey.equals("Large"))
		       	  {
		       		  fsize=3;
		       	  }
		       	if(fontkey.equals("Larger"))
		       	  {
		       		  fsize=4;
		       	  }
		    	if(fontkey.equals("X-Large"))
		       	  {
		       		  fsize=5;
		       	  }
		        }
		        else
		        {
		   	   fsize=ssize;  
		        }

		 
		        DatabaseHandler db = new DatabaseHandler(this);
	    
    	 
        List<Contact> contacts =db.getAllContacts();    
        for (Contact cn : contacts) {  
					int presno=cn.getSno()-1;
					int nextsno=cn.getSno()+1;
					
					DB = new DatabaseHandler(context).getReadableDatabase();
					  Cursor cursor = DB.rawQuery("SELECT * FROM findmercury WHERE sno='"+nextsno+"'", null);   
					  String nsign = "";
					  String nstation;
					  String ntext = "";
					  String dateString="";
					  String nDate="";
					  String y="";
					  String mox="";
					  String d="";
					  
					if (cursor.moveToFirst())
				        {
				      do {
				    	   	 nsign=cursor.getString(3);
				    	   	 nstation=cursor.getString(4);
				    	     dateString=cursor.getString(1);
				    	     y=dateString.substring(0,4); 
				    	     mox=dateString.substring(4,6);
				    	     d=dateString.substring(6,8); 
				    	    
				    	     String  mon = null;
				    	     if (mox.equals("01")) { mon="Jan"; } 
				    	     if (mox.equals("02")) { mon="Feb"; } 
				    	     if (mox.equals("03")) { mon="Mar"; } 
				    	     if (mox.equals("04")) { mon="Apr"; } 
				    	     if (mox.equals("05")) { mon="May"; } 
				    	     if (mox.equals("06")) { mon="Jun"; } 
				    	     if (mox.equals("07")) { mon="Jul"; } 
				    	     if (mox.equals("08")) { mon="Aug"; } 
				    	     if (mox.equals("09"))  { mon="Sep"; } 
				    	     if (mox.equals("10")) { mon="Oct"; } 
				    	     if (mox.equals("11")) { mon="Nov"; } 
				    	     if (mox.equals("12")) { mon="Dec"; } 
				    	     nDate=mon+" "+d+", "+y+" "+dateString.substring(9);   
							if(nstation.equals("SD"))
				            {
							ntext="Direct Station";
		        	        }
							else
							{
							ntext="Retrograde Station";
							}  
				    			 
				      }	while (cursor.moveToNext());
				      cursor.close(); 
				      } 
					
					  Cursor pcursor = DB.rawQuery("SELECT * FROM findmercury WHERE sno='"+presno+"'", null);   
					  String psign = "";
					  String pstation;
					  String ptext = "";
					  String pfromdate = ""; 
					  String ptodate="";
					  String pfry="";
					  String pfrm="";
					  String pfrd="";					  
					  String pfrmdt="";
					  String ptodt = ""; 
					  String ptoy="";
					  String ptom="";
					  String ptod="";
					if (pcursor.moveToFirst())
				        {
				      do {
				    	   	 psign=pcursor.getString(3);
				    	   	 pstation=pcursor.getString(4);
				    	   	 pfrmdt=pcursor.getString(1);
				    	   	 pfry=pfrmdt.substring(0,4); 
				    	   	 pfrm=pfrmdt.substring(4,6);
				    	     pfrd=pfrmdt.substring(6,8); 
				    	    
				    	     String  mon = null;
				    	     if (pfrm.equals("01")) { mon="Jan"; } 
				    	     if (pfrm.equals("02")) { mon="Feb"; } 
				    	     if (pfrm.equals("03")) { mon="Mar"; } 
				    	     if (pfrm.equals("04")) { mon="Apr"; } 
				    	     if (pfrm.equals("05")) { mon="May"; } 
				    	     if (pfrm.equals("06")) { mon="Jun"; } 
				    	     if (pfrm.equals("07")) { mon="Jul"; } 
				    	     if (pfrm.equals("08")) { mon="Aug"; } 
				    	     if (pfrm.equals("09")) { mon="Sep"; } 
				    	     if (pfrm.equals("10")) { mon="Oct"; } 
				    	     if (pfrm.equals("11")) { mon="Nov"; } 
				    	     if (pfrm.equals("12")) { mon="Dec"; } 
				    	     pfromdate=mon+" "+pfrd+", "+pfry+" "+pfrmdt.substring(9); 
				    	   	 
				    	     ptodt=pcursor.getString(2);				    	   	 
				    	     ptoy=ptodt.substring(0,4); 
				    	     ptom=ptodt.substring(4,6);
				    	     ptod=ptodt.substring(6,8); 
				    	    
				    	     String  month = null;
				    	     if (ptom.equals("01")) { month="Jan"; } 
				    	     if (ptom.equals("02")) { month="Feb"; } 
				    	     if (ptom.equals("03")) { month="Mar"; } 
				    	     if (ptom.equals("04")) { month="Apr"; } 
				    	     if (ptom.equals("05")) { month="May"; } 
				    	     if (ptom.equals("06")) { month="Jun"; } 
				    	     if (ptom.equals("07")) { month="Jul"; } 
				    	     if (ptom.equals("08")) { month="Aug"; } 
				    	     if (ptom.equals("09")) { month="Sep"; } 
				    	     if (ptom.equals("10")) { month="Oct"; } 
				    	     if (ptom.equals("11")) { month="Nov"; } 
				    	     if (ptom.equals("12")) { month="Dec"; } 
				    	     ptodate=month+" "+ptod+", "+ptoy+" "+ptodt.substring(9); 
							if(pstation.equals("SD"))
				            {
							ptext="Direct Station";
		        	        }
							else
							{
							ptext="Retrograde Station";
							}  
				    			 
				      }	while (pcursor.moveToNext());
				      pcursor.close();
				      } 
					
					SimpleDateFormat df = new SimpleDateFormat("MMMM dd,yyyy");
					String todate = df.format(Calendar.getInstance().getTime());
					String zs1=cn.getSign();
				     String zodiac1=zs1.toLowerCase();
				     String zs2=nsign;
				     String zodiac2=zs2.toLowerCase();
				     String zs3=psign;
				     String zodiac3=zs3.toLowerCase();
					
					content.setBackgroundResource(R.drawable.bg);
					content.setBackgroundColor(0x00000000);

	//String todate1 = java.text.DateFormat.getDateInstance().format(Calendar.getInstance().getTime());
	String mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
	result="<html><head><style type=\"text/css\">@font-face {font-family: MyFont;src: url('file:///android_asset/fonts/SEGOEPR.TTF')}body {font-family: MyFont; text-align: justify;}</style></head><body>"+"<p align=\"center\"><font color=\"#e2ca72\" size=\""+fsize+"\" >Station of Mercury Today</font></p><h3 align=\"center\"><font color=\"#FF0000\" size=\""+fsize+"\" >"+todate+"</font></h3>"+
	       ""+"<font color=\"#FFffff\" size=\""+fsize+"\" > <div    style=' padding-top:10px; border-radius:30px 5px 30px 5px;  background: linear-gradient(to bottom, #fe7c76, #bf0d00); text-align:justify; line-height:25px;  border: 2px solid #7a6338;  '><div style='float:left;'><img src='red.png' align='absmiddle' width='90' height='90' /></div><div style='color:#000000; text-align:justify; padding:3px; '>"+ "Mercury is in "+cn.getStation()+" in <a href=\"https://www.findyourfate.com/astrology/mercury-retrograde-"+zodiac1+".html\"><font color=\"#FFffff\" size=\""+fsize+"\" face=\"verdana\"><b><u>"+cn.getSign()+"</u></b></font></a> for " + mydate+"</div></div><br><br><div    style=' padding-top:10px; border-radius:30px 5px 30px 5px;  background: linear-gradient(to bottom, #ffd01b, #dcb000); text-align:justify;line-height:25px; color:#000000;   border: 2px solid #7a6338;  '><div style='float:left;'><img src='yellow.png' align='absmiddle' width='90' height='90' /></div> Mercury next goes "+ntext+" in <a href=\"https://www.findyourfate.com/astrology/mercury-retrograde-"+zodiac2+".html\"><font color=\"#FFffff\" size=\""+fsize+"\" face=\"verdana\" ><b><u>"+nsign+"</u></b></font></a> on "+nDate+"</div></div><br><br>"+
           ""+"<div    style=' padding-top:10px; border-radius:30px 5px 30px 5px;  background: linear-gradient(to bottom, #43fa3d, #0ec108); text-align:justify; color:#000000;   border: 2px solid #7a6338; line-height:25px;  '><div style='float:left;'><img src='green.png' align='absmiddle' width='90' height='90' /></div>Mercury was last in "+ptext+" in <a href=\"https://www.findyourfate.com/astrology/mercury-retrograde-"+zodiac3+".html\"><font color=\"#FFffff\" size=\""+fsize+"\" face=\"verdana\"><b><u>"+psign+"</u></b></font></a> on "+ pfromdate+" to "+ptodate+"</div></div><br></font><p align=\"justify\"><font color=\"#FFffff\" size=\"1\" >Note : All time and zodiacal position data are computer generated for the stations of Mercury in geocentric ecliptic longitude (tropical zodiac) with nominal precision to the nearest minute of arc.<font>"+
		    
           ""+"<p align=\"left\"><font color=\"#FFffff\" size=\""+fsize+"\" >For Astrology & Horoscope visit <a href=\"https://www.findyourfate.com\"><font color=\"#FFffff\" size=\""+fsize+"\" >www.findyourfate.com</font></a></font></p><br><br><br><br></body></html>";
	 	 content.loadDataWithBaseURL("file:///android_res/drawable/",result, "text/html", "utf-8",null);  
	 	
	 	 signtext="Mercury is in "+cn.getStation()+" in "+cn.getSign()+" for " + mydate+".\n\n"+
	 		   ""+"Mercury next goes "+ntext+" in "+nsign+" on "+nDate+".\n\n"+
	           ""+"Mercury was last in "+ptext+" in "+psign+" on "+ pfromdate+" to "+ptodate;  
	 
	 	medate=todate;
        } 
        
    	 
        
         
    }

		 

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


return restoredText;
}

/*
@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(todaymercury.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);
        return true; 
    } 
	
	
		 
	@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;
	    
	}
	
	 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(todaymercury.this, todaymercury.class);
				    	icon_home1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			            startActivity(icon_home1);
			  			 
			  		}
			   
			  	});
 	               
 	           popupWindow.showAtLocation(popupView, Gravity.CENTER, 0, 0);
 	             popupWindow.showAsDropDown(popupView, 50, -30);
	 }
}
 
