package mercuryretrograde.findyourfate.com; 
 
import java.text.SimpleDateFormat;

import java.util.Calendar;  


 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; 
public class findsign extends Activity{
	final Context context = this;
	int fsize,ssize ; 
	 private static SQLiteDatabase DB;   
    public static final String MyPREFERENCES = "MyPrefs" ;
    public static final String name = "fontsize";  
    public static SharedPreferences sharedpreferences;
   
	String zodiacsign=null;
	private QuickAction quick;
	ImageView Share;
	 WebView content;  
	 String signtext=null;
	 String medate=null;
	@SuppressLint("NewApi")
	@Override
	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);
		 zodiacsign  =getIntent().getStringExtra("sign");

	        
	  	       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(findsign.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;  
		        }
	 		         
		        DB = new DatabaseHandler(context).getReadableDatabase();    
			    
			 String res_frdt1=null;
			 String res_todt1=null;
			 String res_frdt2=null;
			 String res_todt2=null;
			 String res_frdt3=null;
			 String res_todt3=null;
			 String dateString1="";
			 String dateString2="";
			 String dateString3="";
			 String dateString4="";
			 String dateString5="";
			 String dateString6="";
			 String y1="";
			 String m1="";
			 String d1="";
			 String y2="";
			 String m2="";
			 String d2="";
			 String y3="";
			 String m3="";
			 String d3="";
			 String y4="";
			 String m4="";
			 String d4="";
			 String y5="";
			 String m5="";
			 String d5="";
			 String y6="";
			 String m6="";
			 String d6="";
			
			 Calendar c = Calendar.getInstance();
			 SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd hh:mma");
		     String tday = df.format(c.getTime()); 
		     String zs=zodiacsign;
		     String zodiac=zs.toLowerCase();
			 Cursor cursor = DB.rawQuery("SELECT * FROM mercury WHERE sign='"+zodiacsign+"' and date1>='"+tday+"' and station='SR' order by sno asc LIMIT 1, 3", null);   
			String title="<p align=\"center\"><font color=\"#e2ca72\" size=\""+fsize+"\" >Mercury Retrograde for <b>"+zodiacsign+"</b></font></p><p align=\"justify\">";  
			 
			  int icount=0;
			   if (cursor.moveToFirst())
		      {
					  do { 
						     
				      	  if(icount==0)
				      	  {
				      		dateString1=cursor.getString(1);
				      		dateString2=cursor.getString(2); 
				      		y1=dateString1.substring(0,4); 
				    	    m1=dateString1.substring(4,6);
				    	    d1=dateString1.substring(6,8); 	
				    	    res_frdt1=m1+"/"+d1+"/"+y1+" "+dateString1.substring(9);   
				    	     
			    	         y2=dateString2.substring(0,4); 
				    	     m2=dateString2.substring(4,6);
				    	     d2=dateString2.substring(6,8); 
				    	     res_todt1=m2+"/"+d2+"/"+y2+" "+dateString2.substring(9);
				    	     
				    	     title+="<div style=' padding-top:10px; border-radius:30px 5px 30px 5px;  background: linear-gradient(to bottom, #fe7c76, #bf0d00); text-align:justify;   border: 2px solid #7a6338;line-height:25px;  '><div style='float:left;'><img src='red.png' align='absmiddle' width='90' height='90' /></div><font color=\"#000000\" size=\""+fsize+"\" >Mercury is next retrograde in <a href=\"https://www.findyourfate.com/astrology/mercury-retrograde-"+zodiac+".html\"><font color=\"#FFffff\" size=\""+fsize+"\" face=\"verdana\"><b><u>"+zodiacsign+"</u></b></font></a> on "+res_frdt1 +" to " + res_todt1 +"</font></div></div>";  
				      		 
				      	  }
				      	 if(icount==1)
				      	  {
				      		dateString3=cursor.getString(1);
				      		dateString4=cursor.getString(2);
				      		
				      		y3=dateString3.substring(0,4); 
				    	    m3=dateString3.substring(4,6);
				    	    d3=dateString3.substring(6,8); 
				    	    res_frdt2=m3+"/"+d3+"/"+y3+" "+dateString3.substring(9); 
				    	     
				    	    y4=dateString4.substring(0,4); 
				    	    m4=dateString4.substring(4,6);
				    	    d4=dateString4.substring(6,8); 
				    	    res_todt2=m4+"/"+d4+"/"+y4+" "+dateString4.substring(9);
				    	    
				    	    title+="<br><br><div    style=' padding-top:10px; border-radius:30px 5px 30px 5px;  background: linear-gradient(to bottom, #ffd01b, #dcb000); text-align:justify;   border: 2px solid #7a6338; line-height:25px; '><div style='float:left;'><img src='yellow.png' align='absmiddle' width='90' height='90' /></div><font color=\"#000000\" size=\""+fsize+"\" >The next retrograde in <a href=\"https://www.findyourfate.com/astrology/mercury-retrograde-"+zodiac+".html\"><font color=\"#FFffff\" size=\""+fsize+"\" face=\"verdana\"><b><u>"+zodiacsign+"</u></b></font></a> will be on "+res_frdt2 +" to " + res_todt2 +"</font></div></div>";
				      		 
					 	  }
				      	if(icount==2)
				      	  {
				      		dateString5=cursor.getString(1);
				      		dateString6=cursor.getString(2);
				      		
				      		y5=dateString5.substring(0,4); 
				    	    m5=dateString5.substring(4,6);
				    	    d5=dateString5.substring(6,8); 
				    	    res_frdt3=m5+"/"+d5+"/"+y5+" "+dateString5.substring(9); 
				    	     
			    	        y6=dateString6.substring(0,4); 
				    	    m6=dateString6.substring(4,6);
				    	    d6=dateString6.substring(6,8); 
				    	    res_todt3=m6+"/"+d6+"/"+y6+" "+dateString6.substring(9); 
				    	    
				    	    title+="<br><br>  <div    style=' padding-top:10px; border-radius:30px 5px 30px 5px;  background: linear-gradient(to bottom, #43fa3d, #0ec108); text-align:justify;   border: 2px solid #7a6338; line-height:25px; '><div style='float:left;'><img src='green.png' align='absmiddle' width='90' height='90' /></div><font color=\"#000000\" size=\""+fsize+"\" >Another mercury retrograde in <a href=\"https://www.findyourfate.com/astrology/mercury-retrograde-"+zodiac+".html\"><font color=\"#FFffff\" size=\""+fsize+"\" face=\"verdana\"><b><u>"+zodiacsign+"</u></b></font></a> occurs on "+res_frdt3 +" to " + res_todt3 +"</font></div></div>";
				      		 
						   }
						    icount=icount+1;
					}while (cursor.moveToNext()); 
					  cursor.close(); 
			       }
			   else
				  {
					  
				   title="<center><font color=\"#FFffff\" size=\""+fsize+"\"><b>No Records Found</b></font>"; 
					  cursor.close();
				  } 
			      title+="</p><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>"+
			      ""+"<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.setBackgroundResource(R.drawable.bg);
					content.setBackgroundColor(0x00000000);    
				 
			      content.loadDataWithBaseURL("file:///android_res/drawable/","<html><style type=\"text/css\">@font-face {font-family: MyFont;src: url('file:///android_asset/arial.ttf')}body {font-family: MyFont; text-align: justify;}</style></head><body>"+title+"</body></html>", "text/html", "utf-8",null);
			      signtext="Mercury is next retrograde in "+zodiacsign+" on "+res_frdt1 +" to " + res_todt1 +".\n\n"+
				            ""+"The next retrograde in "+zodiacsign+" will be on "+res_frdt2 +" to " + res_todt2 +".\n\n"+
				           ""+"Another mercury retrograde in "+zodiacsign+" occurs on "+res_frdt3 +" to " + res_todt3;  
	} 
	 

	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 boolean onCreateOptionsMenu(Menu menu)
    {
		getMenuInflater().inflate(R.menu.main_menu, menu);
        return true; 
    } 
	  
	/*  @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(zodiacsign.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 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 void createDataBase() throws IOException
     {
         //If database not exists copy it from the assets
     	 
         boolean mDataBaseExist = checkDataBase();
         if(!mDataBaseExist)
         {
             this.getReadableDatabase();
             this.close();
             try 
             {
                 //Copy the database from assests
                 copyDataBase();
                 Log.e(TAG, "createDatabase database created");
             } 
             catch (IOException mIOException) 
             {
                 throw new Error("ErrorCopyingDataBase");
             }
         }
     }
     private void getReadableDatabase() {
		// TODO Auto-generated method stub
		
	}
	private boolean checkDataBase()
     {
       
     	 
     	File dbFile = mContext.getDatabasePath(DATABASE_NAME);
         SQLiteDatabase checkDB = null;
         
     	try{
     		checkDB = SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READONLY);
  
     	}catch(SQLiteException e){
  
     		//database does't exist yet.
  
     	}
  
     	if(checkDB != null){
  
     		checkDB.close();
  
     	}
  
     	return checkDB != null ? true : false;
         
     }

	
	 private void copyDataBase() throws IOException
     {
		 File dbFile = context.getDatabasePath(DATABASE_NAME);		  
	     InputStream mInput = this.getAssets().open(DATABASE_NAME);
         OutputStream mOutput = new FileOutputStream(dbFile);
         byte[] mBuffer = new byte[1024];
         int mLength;
         while ((mLength = mInput.read(mBuffer))>0)
         {
             mOutput.write(mBuffer, 0, mLength);
         }
         mOutput.flush();
         mOutput.close();
         mInput.close();
     }
	 public void openDataBase() throws SQLException
	    {
	    	File dbFile = mContext.getDatabasePath(DATABASE_NAME);
	        
	      mDataBase = SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READONLY);
	       // mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.OPEN_READONLY);
	        
	    }

	    public synchronized void close() 
	    {
	        if(mDataBase != null)
	            mDataBase.close();
	        try {
				super.clone();
			} catch (CloneNotSupportedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    }
	    public void onCreate(SQLiteDatabase db) {
	         String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
	         		+ KEY_SNO + " INTEGER PRIMARY KEY AUTOINCREMENT,"  
	                 + KEY_DATE1 + " TEXT," + KEY_DATE2 + " TEXT,"
	                 + KEY_TIME1 + " TEXT,"
	                 + KEY_TIME2 + " TEXT" + ")";
	         db.execSQL(CREATE_CONTACTS_TABLE);
	     }
	  
	     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	         db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS); 
	         onCreate(db);
	 } 
	     */ 
	 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(findsign.this, findsign.class);
				    	icon_home1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			            startActivity(icon_home1);
			  			 
			  		}
			   
			  	});
 	               
 	           popupWindow.showAtLocation(popupView, Gravity.CENTER, 0, 0);
 	             popupWindow.showAsDropDown(popupView, 50, -30);
	 }
}
