package astrology.findyourfate.com;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xmlpull.v1.XmlSerializer;
import com.google.analytics.tracking.android.EasyTracker;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.util.Xml;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ImageView;


public class home  extends Activity {
	 private EasyTracker easyTracker = null;
	String fname="myfile.xml";
	@Override
 protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	    setContentView(R.layout.home);
	    easyTracker = EasyTracker.getInstance(home.this);
	    Runnable swapImage = new Runnable() {
		    @Override
		    public void run() {
		  	File myFile = new File(getFilesDir() + "/" + fname);
		    		if (myFile.exists()) 
		            {
		    			try {
			    	FileInputStream file = new FileInputStream(new File(getFilesDir() + "/" + fname));
				     DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
				     DocumentBuilder builder =  builderFactory.newDocumentBuilder();
				     Document xmlDocument = builder.parse(file);
					  XPath xPath =  XPathFactory.newInstance().newXPath();
				       System.out.println("*************************");
					           String   expression = "/root/zodiac";
					           System.out.println(expression);
					           String   expressio = "/root/dob";
					           System.out.println(expressio);
					         
					              NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
					            
					            for (int i = 0; i < nodeList.getLength(); i++) {
					            	
					              String value=nodeList.item(i).getFirstChild().getNodeValue(); 
					               
					               NodeList nodeList1 = (NodeList) xPath.compile(expressio).evaluate(xmlDocument, XPathConstants.NODESET);
						            
						            for (int i1 = 0; i1 < nodeList1.getLength(); i1++) {
						               String val=nodeList1.item(i1).getLastChild().getNodeValue(); 
						  		       
					           if(value.equals(""))
					           {
					        	   Intent int_ast = new Intent(home.this,astology.class);
						            int_ast.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						            startActivity(int_ast);	
					           }
					           else
					           {
					            	Intent ins= new Intent(home.this,findzodiac.class);
									 ins.putExtra("date",val);
									  ins.putExtra("key", value);
									  ins.putExtra("modeday","Today");							
									startActivity(ins);
					           }
					            }
					            
					            }
							}catch (FileNotFoundException e) {
					            e.printStackTrace();
							} catch (SAXException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (ParserConfigurationException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (XPathExpressionException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}			
 		            }
		    		else
		    		{ 
		    			  FileOutputStream fos = null;       
		    			  	try{
						        	  fos = openFileOutput(fname,Context.MODE_APPEND);

			        	       }catch(FileNotFoundException e){
						                Log.e("FileNotFoundException", "can't create FileOutputStream");
						        }
				    
						        XmlSerializer serializer = Xml.newSerializer();
						        try {
						        	
						                    serializer.setOutput(fos, "UTF-8");
						                    serializer.startDocument(null, Boolean.valueOf(true));
						                    serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
						                    serializer.startTag(null, "root"); 
						                    serializer.startTag(null, "zodiac"); 
						                    serializer.text("Cancer"); 
						                    serializer.endTag(null, "zodiac"); 
						                    serializer.startTag(null, "dob"); 
						                    serializer.text("18/7/2014"); 
							                serializer.endTag(null, "dob"); 
							                serializer.endTag(null, "root");
						                    serializer.endDocument();
						            	    serializer.flush();
						                    fos.close();
						        } catch (Exception e) {
						                        Log.e("Exception","error occurred while creating xml file");
						                } 
						 Intent int_ast = new Intent(home.this,astology.class);
				         int_ast.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				         startActivity(int_ast);		
		    		}
					}
		    
	    };
	   ImageView  img = (ImageView) findViewById(R.id.imageView1);
	   img.postDelayed(swapImage,2000);
}
	
	@Override
    public void onStart() {
        super.onStart();
        EasyTracker.getInstance(this).activityStart(this);
    }
 
    @Override
    public void onStop() {
        super.onStop();
        EasyTracker.getInstance(this).activityStop(this);
    }
	@Override
    public void onBackPressed() {
		 AlertDialog.Builder builder = new AlertDialog.Builder(this);
		    builder.setMessage("Are you sure want to exit from Astrology 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.show();	
   }
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	MenuInflater inflater = getMenuInflater();
	inflater.inflate(R.menu.main, menu); 
		return super.onCreateOptionsMenu(menu);
	}
	    
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		 if (item.getItemId() == R.id.drawer)
		 {
					 Intent int_dr = new Intent(this,MainActivity.class);
			            int_dr.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			            startActivity(int_dr);
		 }
		 else if (item.getItemId() ==R.id.service)
		 {
			  Intent int_ser = new Intent(this,ourservices.class);
	            int_ser.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	            startActivity(int_ser);
		 }
		 else	 if (item.getItemId() ==R.id.astrology)
		 {
				File myFile = new File(getFilesDir() + "/" + fname);
				
					        if (myFile.exists()) 
				            {
					        	try {
					    			
					        	   FileInputStream file = new FileInputStream(new File(getFilesDir() + "/" + fname));
						            DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
						             
						            DocumentBuilder builder =  builderFactory.newDocumentBuilder();
						             
						            Document xmlDocument = builder.parse(file);
						 
						            XPath xPath =  XPathFactory.newInstance().newXPath();
						   
						            System.out.println("*************************");
						           String   expression = "/root/zodiac";
						            System.out.println(expression);
						            NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
						            for (int i = 0; i < nodeList.getLength(); i++) {
						               String value=nodeList.item(i).getLastChild().getNodeValue(); 
						               if(value.length() == 0)
						               {
						               Intent int_ast = new Intent(this,astology.class);
							            int_ast.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							            startActivity(int_ast);
						               }
						               else
						               {
										Intent in= new Intent(this,horoscope.class);
										  in.putExtra("key", value);
									in.putExtra("modeday","Today");							
										startActivity(in);
							     
						            	}
						           	
									}   

								}catch (FileNotFoundException e) {
						            e.printStackTrace();
								} catch (SAXException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} catch (ParserConfigurationException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} catch (XPathExpressionException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}			
 
				            }
				                    
					        else
				            {
				            	 Intent int_ast = new Intent(this,astology.class);
						            int_ast.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						            startActivity(int_ast);
					       }
		 }
		 else if (item.getItemId() ==R.id.setup)
		 {
			File myFile1 = new File(getFilesDir() + "/" + fname);
			    if (myFile1.exists()) 
				            {
					        	
					        	try {  	
					        	FileInputStream file = new FileInputStream(new File(getFilesDir() + "/" + fname));
						               
						            DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
						             
						            DocumentBuilder builder =  builderFactory.newDocumentBuilder();
						             
						            Document xmlDocument = builder.parse(file);
						 
						            XPath xPath =  XPathFactory.newInstance().newXPath();
						   
						          System.out.println("*************************");
						          String   expression = "/root/zodiac";
						         
						          System.out.println(expression);
						          String   expressio = "/root/dob";
						         
							      System.out.println(expressio);
							         
							              NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
							            
							            for (int i = 0; i < nodeList.getLength(); i++) {
							            	
							                     	
							               String value=nodeList.item(i).getFirstChild().getNodeValue(); 
							               
							             
							               NodeList nodeList1 = (NodeList) xPath.compile(expressio).evaluate(xmlDocument, XPathConstants.NODESET);
								            
								            for (int i1 = 0; i1 < nodeList1.getLength(); i1++) {
								            	
								                     	
								               String val=nodeList1.item(i1).getLastChild().getNodeValue(); 
								             
								     if(value.length() == 0)
						               {
						               Intent int_ast = new Intent(this,astology.class);
							            int_ast.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							            startActivity(int_ast);
						               }
						               else
						               {
										Intent in= new Intent(this,setuppage.class);
										 in.putExtra("date",val);
										  in.putExtra("key", value);
										  in.putExtra("modeday","Today");	
											startActivity(in);
							           }
						            }   
							     }
				           }catch (FileNotFoundException e) {
					            e.printStackTrace();
							} catch (SAXException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (ParserConfigurationException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (XPathExpressionException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
				            }
						          
				            else
				            {
				            	 Intent int_ast = new Intent(this,astology.class);
						         int_ast.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						         startActivity(int_ast);
				            }       
		 }
		 else if (item.getItemId() == R.id.exit)
		  {
			  Intent intent = new Intent(Intent.ACTION_MAIN);
		      intent.addCategory(Intent.CATEGORY_HOME);
		      intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		      startActivity(intent);
		  }
	/*	 else  if (item.getItemId() ==R.id.share)
		 {
        	 	 Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
     	    	emailIntent.setType("text/plain");
     	    	 emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "our services - findyourfate.com");
             	 emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml("<p>Hi,<br><br>I would like to suggest, this find your fate App to you. <br>To Download this apps <a href=\"https://play.google.com/store/apps/details?id=com.findyourfate.com.services\"><b>Click Here</b></a></p>"));
     	    	startActivity(emailIntent);
		 }
		 else if (item.getItemId() == R.id.in)
		  {
			  AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(home.this);
			    alertDialogBuilder.setTitle("Horoscope Compatibility");
			
			           alertDialogBuilder.setMessage("Compatibility of zodiac signs for love and romantic relationship. Search what zodiac signs are compatible. Find quality results here!No two sun signs are alike and totally compatible. A degree of incompatibility always exists because that is how we have been made.Marriages are made in heaven BUT!!! Compatible Love Matches are made here through this app.The paid in-app compatibility report is \"the best buy\".");
			     alertDialogBuilder.setPositiveButton("Open",new DialogInterface.OnClickListener() {
			        	   
			        	                   public void onClick(DialogInterface dialog,int id) {
			        	                	   final String appPackageName = "compatibility.findyourfate.com"; // getPackageName() from Context or Activity object
			        	                	   try {
			        	                	       startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
			        	                	   } catch (android.content.ActivityNotFoundException anfe) {
			        	                	       startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + appPackageName)));
			        	                	   }
			        	                   }
			        	                   });
			          alertDialogBuilder.setNeutralButton("Already/Never",new DialogInterface.OnClickListener() {
			                  public void onClick(DialogInterface dialog,int id) {	  
			                    //  MainActivity.this.finish();
			                	  dialog.cancel();
			                  }
			  
			              });
			  
			            // set negative button: No message
				    	alertDialogBuilder.setNegativeButton("Later",new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog,int id) {
			                      // cancel the alert box and put a Toast to the user
			                      dialog.cancel();                    
			                  }
			              });
			           AlertDialog alertDialog = alertDialogBuilder.create();
			 
			           // show alert
			           alertDialog.show();			  
			  } */
		 else
		 {
		 }   
			return true;
		}
	
	public boolean fileExistance(String fname){
	    File myfile = getBaseContext().getFileStreamPath(fname);
	    return myfile.exists();
	}
}
