package mercuryretrograde.findyourfate.com;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.ParseException;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.telephony.TelephonyManager;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast; 
public class MercuryRetrogradeActivity extends Activity {
	

	    TextView tv,tvn, da,dan,h1,m1,s1,dt,mt,st,ht,sn1,hn1,mn1,stn,dtn,mtn,snt,htn;
	    long diff;
	    long milliseconds;
	    long endTime;
	    final Context context = this;   
	    protected SQLiteDatabase DB;
		protected Cursor cursor; 
		String dateString="";
		 int  ssize;
		 TableRow t1,t2,t3,t4;
		 
    /** Called when the activity is first created. */ 
    //@Override 
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    	String userAgent = new WebView(context).getSettings().getUserAgentString();
    	  if (userAgent.contains("Mobile")) {
        	// Toast.makeText(this, "phone",Toast.LENGTH_LONG).show();
        	  setContentView(R.layout.activity_main); 
        }else{
        	//Toast.makeText(this, "tab",Toast.LENGTH_LONG).show();
      	  setContentView(R.layout.activity_maintab); 
        }
        
        
        Intent intent = getIntent();
        String action = intent.getAction();
        Uri data = intent.getData();        
         
        t1 = (TableRow) findViewById(R.id.nowmer1);
  		t2 = (TableRow) findViewById(R.id.nowmer2);
  		t3 = (TableRow) findViewById(R.id.nowmer3);
  		t4 = (TableRow) findViewById(R.id.nowmer4);
  		
  	    ImageView about = (ImageView) findViewById(R.id.about);
  		ImageView find = (ImageView) findViewById(R.id.find);
  		ImageView cal = (ImageView) findViewById(R.id.cal);
  		ImageView sign = (ImageView) findViewById(R.id.sign);
  		ImageView notify = (ImageView) findViewById(R.id.notify);
  		// tv = new TextView(this);
  		 addnowmercury();
  		 addHeaders();
  	  	tv = (TextView) findViewById(R.id.nextmerto);
  	  	da= (TextView) findViewById(R.id.day);
  		h1= (TextView) findViewById(R.id.hrs);
  		m1= (TextView) findViewById(R.id.mts);
  		s1= (TextView) findViewById(R.id.secs); 
  	  	 dt= (TextView) findViewById(R.id.daytext);
  		ht= (TextView) findViewById(R.id.hrstext);
  		mt= (TextView) findViewById(R.id.mtstext);
  		st= (TextView) findViewById(R.id.secstext);  		
  	    tvn = (TextView) findViewById(R.id.nowmerto);
	  	dan= (TextView) findViewById(R.id.daynow);
		hn1= (TextView) findViewById(R.id.hrsnow);
		mn1= (TextView) findViewById(R.id.mtsnow);
		sn1= (TextView) findViewById(R.id.secsnow); 
	  	 dtn= (TextView) findViewById(R.id.daytextn);
		htn= (TextView) findViewById(R.id.hrstextn);
		mtn= (TextView) findViewById(R.id.mtstextn);
		stn= (TextView) findViewById(R.id.secstextn);
		
  		
  		
  		 
  	  DisplayMetrics metrics = new DisplayMetrics(); 
      Activity activity = (Activity) context;
      activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
       

  		
  	 
    if (userAgent.contains("Mobile")) {
   
if (metrics.densityDpi <= DisplayMetrics.DENSITY_LOW) {
	//Toast.makeText(this, "low screen",Toast.LENGTH_LONG).show();
	ssize=10;
	 
} else if (metrics.densityDpi <= DisplayMetrics.DENSITY_HIGH) {
	// Toast.makeText(this, "high screen",Toast.LENGTH_LONG).show();
	ssize=14;
	 
}
else if (metrics.densityDpi <= DisplayMetrics.DENSITY_MEDIUM) {
	// Toast.makeText(this, "medium screen",Toast.LENGTH_LONG).show();
	ssize=12;
	 
}
else if (metrics.densityDpi <= DisplayMetrics.DENSITY_XHIGH) {
	 //Toast.makeText(this, "xLarge screen",Toast.LENGTH_LONG).show();
	ssize=16;
	 
}
else if (metrics.densityDpi <= DisplayMetrics.DENSITY_XXHIGH) {
	// Toast.makeText(this, "xxLarge screen",Toast.LENGTH_LONG).show();
	ssize=18;
	 
}
else if (metrics.densityDpi <= DisplayMetrics.DENSITY_XXXHIGH) {
	 
	ssize=20;
	 
}
else {
	 
	ssize=16;
	 
}
tv.setTextSize(ssize);
tvn.setTextSize(ssize);
    }
    else
    {
    	tv.setTextSize(20); 
    	tvn.setTextSize(20);
    	ssize=18;
    }
  		 //tv = new TextView(this);
        // this.setContentView(tv);
    
   
    
    da.setTextSize(ssize);
    h1.setTextSize(ssize);
    m1.setTextSize(ssize);
    s1.setTextSize(ssize);
    dt.setTextSize(ssize);
    ht.setTextSize(ssize);
    mt.setTextSize(ssize);
    st.setTextSize(ssize);
 
    
    dan.setTextSize(ssize);
    hn1.setTextSize(ssize);
    mn1.setTextSize(ssize);
    sn1.setTextSize(ssize);
    dtn.setTextSize(ssize);
    htn.setTextSize(ssize);
    mtn.setTextSize(ssize);
    stn.setTextSize(ssize);

  		 
  

 about.setOnClickListener(new OnClickListener() {
		@Override
			public void onClick(View arg0) {
			         Intent intent = new Intent(context, contentmercury.class);
				  	 startActivity(intent); 
		        	}
		      	});
 
 find.setOnClickListener(new OnClickListener() {
		@Override
			public void onClick(View arg0) {

			         Intent intent = new Intent(context, todaymercury.class);
				   	 startActivity(intent); 
		        	}

		      	});
 cal.setOnClickListener(new OnClickListener() {
		@Override
			public void onClick(View arg0) {

			         Intent intent = new Intent(context, calendar.class);
				   	 startActivity(intent); 

		        	}
		      	});
 sign.setOnClickListener(new OnClickListener() {
		@Override
			public void onClick(View arg0) {
			         Intent intent = new Intent(context, zodiacsign.class);
				   	 startActivity(intent); 
		        	}
		      	});
 
 notify.setOnClickListener(new OnClickListener() {
		@Override
			public void onClick(View arg0) {

       	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")); 

		        	}
		      	});
 	}
	
	
	@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 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();

     }
	 public void addHeaders(){
		 
		
	       
         SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd HH:mm");
         formatter.setLenient(false);
         DatabaseHandler db = new DatabaseHandler(this);
 	    
    	 
         List<Contact> contacts =db.getAllContacts();    
         for (Contact cn : contacts) {  
 				 
 					int nextsno=cn.getupSno();
 					DB = new DatabaseHandler(context).getReadableDatabase();
 					  Cursor cursor = DB.rawQuery("SELECT * FROM findmercury WHERE sno='"+nextsno+"'", null);  
 					  
 					if (cursor.moveToFirst())
 				        {
 				      do {
 				    	    
 				    	     dateString=cursor.getString(1);
 				    	   //  y=dateString.substring(0,4); 
 				    	    // mox=dateString.substring(4,6);
 				    	    // d=dateString.substring(6,8); 
 				    	     
 				    			 
 				      }	while (cursor.moveToNext());
 				      cursor.close(); 
 				      } 
 					
         } 
         
  
 		//  Toast.makeText(context,"dateString="+dateString,Toast.LENGTH_LONG).show();
 		
         // String oldTime = "20170409 12:00";
 		
 		
         
         
         
         String oldTime =dateString;
         if ( (oldTime.equals("")) || (oldTime.equals(null)))
         {
         	t3.setVisibility(View.GONE);
         	t4.setVisibility(View.GONE);
         }
         else
         {
         Date oldDate = null;
         try {
             oldDate = formatter.parse(oldTime);
              milliseconds = oldDate.getTime();

             //long startTime = System.currentTimeMillis();
             // do your work...
           /*  long endTime=System.currentTimeMillis();

              diff = milliseconds-endTime;       

            // Log.e("day", "miliday"+diff);
             long seconds = (long) (diff / 1000) % 60 ;
             //Log.e("secnd", "miliday"+seconds);
             long minutes = (long) ((diff / (1000*60)) % 60);
            // Log.e("minute", "miliday"+minutes);
             long hours   = (long) ((diff / (1000*60*60)) % 24);
            // Log.e("hour", "miliday"+hours);
             long days = (int)((diff / (1000*60*60*24)) % 365);
            // Log.e("days", "miliday"+days);*/
         } catch (ParseException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         } catch (java.text.ParseException e) {
 			// TODO Auto-generated catch block
 			e.printStackTrace();
 		}
         milliseconds = oldDate.getTime();
         MyCount counter = new MyCount(milliseconds,1000);
         counter.start();
	    }
	 }

 
	 // countdowntimer is an abstract class, so extend it and fill in methods
    public class MyCount extends CountDownTimer {
        public MyCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
           // tv.setText("done!");
        	addHeaders();
        }

        @Override
        public void onTick(long millisUntilFinished) {
            //tv.setText("Left: " + millisUntilFinished / 1000);
             
            Long serverUptimeSeconds =  (millisUntilFinished-System.currentTimeMillis()) / 1000;

            
            long seconds = ((serverUptimeSeconds % 86400) % 3600 ) % 60 ;
            //Log.e("secnd", "miliday"+seconds);
            long minutes = (long) ((serverUptimeSeconds % 86400) % 3600 ) / 60;
            //Log.e("minute", "miliday"+minutes);
            long hours   = (long) ( serverUptimeSeconds % 86400) / 3600;
            //Log.e("hour", "miliday"+hours);
            int days = (int)(serverUptimeSeconds / 86400);
                    
                   // tv.setText(Html.fromHtml("Next Mercury Retro "));
                    
                    da.setText(String.valueOf(" "+days+" "));
                    h1.setText(String.valueOf(" "+hours+" "));
                    m1.setText(String.valueOf(" "+minutes+" "));
                    s1.setText(String.valueOf(" "+seconds+" "));
                    
        }
         
}
    public void addnowmercury(){
		 
		
	       
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd HH:mm");
        formatter.setLenient(false);
        DatabaseHandler db = new DatabaseHandler(this);
	    
   	 
        List<Contact> contacts =db.getAllContacts();    
        for (Contact cn : contacts) {  
				 
					int nowsno=cn.getnowsno();
					DB = new DatabaseHandler(context).getReadableDatabase();
					  Cursor cursor = DB.rawQuery("SELECT * FROM findmercury WHERE sno='"+nowsno+"'", null);  
					  
					if (cursor.moveToFirst())
				        {
				      do {
				    	    
				    	     dateString=cursor.getString(2);
				    	   //  y=dateString.substring(0,4); 
				    	    // mox=dateString.substring(4,6);
				    	    // d=dateString.substring(6,8); 
				    	     
				    			 
				      }	while (cursor.moveToNext());
				      cursor.close(); 
				      } 
					
					  
					 
				 
        } 
        
 
	// Toast.makeText(context,"dateString="+dateString,Toast.LENGTH_LONG).show();
		
        // String oldTime = "20170409 12:00";
		
		
        
        
        
        String oldTime =dateString;
        if ( (oldTime.equals("")) || (oldTime.equals(null)))
        {
        	t1.setVisibility(View.GONE);
        	t2.setVisibility(View.GONE);
        }
        else
        {
        Date oldDate = null;
        try {
            oldDate = formatter.parse(oldTime);
             milliseconds = oldDate.getTime();

             
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (java.text.ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        milliseconds = oldDate.getTime();
        MyCount1 counter = new MyCount1(milliseconds,1000);
        counter.start();
        }
	    }


	 // countdowntimer is an abstract class, so extend it and fill in methods
   public class MyCount1 extends CountDownTimer {
       public MyCount1(long millisInFuture, long countDownInterval) {
           super(millisInFuture, countDownInterval);
       }

       @Override
       public void onFinish() {
          // tv.setText("done!");
    	   addnowmercury();
       }

       @Override
       public void onTick(long millisUntilFinished) {
           //tv.setText("Left: " + millisUntilFinished / 1000);
            
           Long serverUptimeSeconds =  (millisUntilFinished-System.currentTimeMillis()) / 1000;

           
           long seconds = ((serverUptimeSeconds % 86400) % 3600 ) % 60 ;
           //Log.e("secnd", "miliday"+seconds);
           long minutes = (long) ((serverUptimeSeconds % 86400) % 3600 ) / 60;
           //Log.e("minute", "miliday"+minutes);
           long hours   = (long) ( serverUptimeSeconds % 86400) / 3600;
           //Log.e("hour", "miliday"+hours);
           int days = (int)(serverUptimeSeconds / 86400);
                   
                //   tvn.setText(Html.fromHtml("Next Mercury Retro "));
                   
                   dan.setText(String.valueOf(" "+days+" "));
                   hn1.setText(String.valueOf(" "+hours+" "));
                   mn1.setText(String.valueOf(" "+minutes+" "));
                   sn1.setText(String.valueOf(" "+seconds+" "));
                   
       }
        
}
}