package astrology.findyourfate.com;

import java.io.FileInputStream;


import com.amazon.device.ads.AdLayout;
import com.amazon.device.ads.AdRegistration;
import com.amazon.device.ads.AdTargetingOptions;
import com.google.analytics.tracking.android.EasyTracker; 
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.File; 
import java.text.SimpleDateFormat;
import java.util.Calendar; 
import java.util.Locale;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent; 
import android.os.Bundle; 
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ShareActionProvider; 
	public class astology extends Activity {
				String sign=null;
				// private AdView mAdview;
				 private AdLayout adView;
				 String fname="myfile.xml";
				 EditText dat;
				 String month,day,year1;
				 private ShareActionProvider mShareActionProvider;
				 private EasyTracker easyTracker = null;
				int y,m,d;
				
		 @Override
		 protected void onCreate(Bundle savedInstanceState) {
		        super.onCreate(savedInstanceState);

		        setContentView(R.layout.astrology);
				 // mAdview = (AdView) findViewById(R.id.adView);
			      //  mAdview.setAdListener(new ToastAdListener(this));
		        AdRegistration.setAppKey("fbce94eb2ff347e5a855d4496106f125");
			 	   this.adView = (AdLayout) findViewById(R.id.ad_view);
				AdTargetingOptions adOptions = new AdTargetingOptions();
				AdRegistration.enableLogging(false);
				 AdRegistration.enableTesting(false);
			        dat=(EditText)findViewById(R.id.dateofbirth);
			        getActionBar().setDisplayHomeAsUpEnabled(true);   
			        easyTracker = EasyTracker.getInstance(astology.this);
			        final Button b1=(Button) findViewById(R.id.find);  	
					  
			        final Calendar myCalendar = Calendar.getInstance();
			        final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {

				       @Override
				       public void onDateSet(DatePicker view, int year, int monthOfYear,
				                    int dayOfMonth) {
				           // TODO Auto-generated method stub
				    	   
				    	   
				    	    myCalendar.set(Calendar.YEAR, year);
					           myCalendar.set(Calendar.MONTH, monthOfYear);
					           myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
					            y=myCalendar.get(Calendar.YEAR);
					            m= myCalendar.get(Calendar.MONTH) + 1 ;
					        	d=  myCalendar.get(Calendar.DAY_OF_MONTH);
					        	// Toast.makeText(astology.this, "date:"+d+"/"+m+"/"+y, Toast.LENGTH_LONG).show();
					 	            updateLabel();
					        	}
				            
				       private void updateLabel() {

				            String myFormat = "dd/MM/yyyy"; //In which you need put here
				            SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
				            	dat.setText(sdf.format(myCalendar.getTime()));
				            }
				       	 };
				       	 
				       	 dat.setOnClickListener(new OnClickListener() {
			        	   @Override
			                public void onClick(View v) {
			                    // TODO Auto-generated method stub
			                    new DatePickerDialog(astology.this, date, myCalendar
			                   .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
			                    myCalendar.get(Calendar.DAY_OF_MONTH)).show();
			                 }
			            });
					    	// mAdview.loadAd(new AdRequest.Builder().build());
				       	this.adView.loadAd(adOptions);
		
	 	           final AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
    	  		 b1.setOnClickListener(new View.OnClickListener() {
			 				@Override
							public void onClick(View v) {
								// TODO Auto-generated method stub
								if(dat.getText().toString().length() == 0 )
					         	{
					         		 alt_bld.setTitle("Alert Message");
					         		 alt_bld.setMessage("Please Select  your Date of Birth")
					         		 .setCancelable(false)
					         					 .setPositiveButton("OK", new DialogInterface.OnClickListener() {
					         					 public void onClick(DialogInterface dialog, int id) {
					         						dat.requestFocus(); 
					         					 }
					         					 });
					         		 AlertDialog alert = alt_bld.create();
					         		 alert.setTitle("Alert Message");
					         		 alert.setIcon(R.drawable.alert);
					         		 alert.show();
					         		 dat.setFocusable(true);
					         	}
					     	    
				        		 else  if(!(dat.getText().toString().length() == 0))
								{
				        			 int intDay =d;
				        			 int intMonth =m;	
				        			 int intYear =y;	
				        			 
				        			 if ((intDay >= 20 && intMonth == 1) || (intDay <= 18 && intMonth ==2)) 
				 					{
				 								sign = "Aquarius";
				 					}
				        			 else if ((intDay >= 19 && intMonth == 2)|| (intDay <= 20 && intMonth == 3)) 
				        			 {
				 								sign = "Pisces";
				        			 }
				        			 else if ((intDay >= 21 && intMonth == 3) || (intDay <= 19 && intMonth == 4))
				        			 {
				 								sign = "Aries";
				        			 }
				        			 else if ((intDay >= 20 && intMonth == 4) || (intDay <= 20 && intMonth == 5))
				        			 {
				 								sign = "Taurus";
				        			 }
				        			 else if ((intDay >= 21 && intMonth == 5) || (intDay <= 21 && intMonth == 6))
				        			 {
				 								sign = "Gemini";
				        			 }
				        			 else if ((intDay >= 22 && intMonth == 6) || (intDay <= 22 && intMonth == 7))
				        			 {
				 								sign = "Cancer";
				        			 }
				        			 else if ((intDay >= 23 && intMonth == 7) || (intDay <= 22 && intMonth == 8)) 
				        			 {
				 								sign = "Leo";
				        			 }
				        			 else if ((intDay >= 23 && intMonth == 8) || (intDay <= 22 && intMonth == 9))
				        			 {
				 								sign = "Virgo";
				        			 }
				        			 else if ((intDay >= 23 && intMonth == 9) || (intDay <= 22 && intMonth == 10))
				        			 {
				 								sign= "Libra";
				        			 }
				        			 else if ((intDay >= 23 && intMonth == 10) || (intDay <= 21 && intMonth == 11))
				        			 {
				 								sign = "Scorpio";
				        			 }
				        			 else if ((intDay >= 22 && intMonth == 11)|| (intDay <= 21 && intMonth == 12))
				        			 {
				 								sign = "Sagittarius";
				        			 }
				        			 else if ((intDay >= 22 && intMonth == 12)||(intDay <= 19 && intMonth == 1))
				        			 {
				 								sign = "Capricorn";
				        			 }
				        		
				        			 try {
				        				 				        
				        				   FileInputStream filepath = new FileInputStream(new File(getFilesDir() + "/" + fname));
					 				    	DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
				        					DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
				        					Document doc = docBuilder.parse(filepath);
				        					Node root = doc.getFirstChild();
				        					NodeList list = root.getChildNodes();
				        				
				        					for (int i = 0; i < list.getLength(); i++) {
				        						 
				        		                   Node node = list.item(i);
				        		 
				        				
				        				   if ("zodiac".equals(node.getNodeName())) {
				        					node.setTextContent(sign);
				        				   }
				        				   if ("dob".equals(node.getNodeName())) {
					        					node.setTextContent(d+"/"+m+"/"+intYear);
					        				   }
					        					}
				        					TransformerFactory transformerFactory = TransformerFactory.newInstance();
				        					Transformer transformer = transformerFactory.newTransformer();
				        					DOMSource source = new DOMSource(doc);
				        					StreamResult result = new StreamResult(new File(getFilesDir() + "/" + fname));
				        					transformer.transform(source, result);
				        			 
				        					System.out.println("Done");
				        			 
				        				   } catch (ParserConfigurationException pce) {
				        					pce.printStackTrace();
				        				   } catch (TransformerException tfe) {
				        					tfe.printStackTrace();
				        				   } catch (IOException ioe) {
				        					ioe.printStackTrace();
				        				   } catch (SAXException sae) {
				        					sae.printStackTrace();
				        				   }
				        		 
				     		       Intent in=new Intent(astology.this,findzodiac.class);
				 					in.putExtra("date",intDay+"/"+intMonth+"/"+y);
									 in.putExtra("key",sign);
			        				in.putExtra("modeday","Today");							
									startActivity(in);
									
									  boolean hasActionBar = android.os.Build.VERSION.SDK_INT >= 11;
									  if (hasActionBar) {
								             ActionBar actionBar = getActionBar();
								             actionBar.setHomeButtonEnabled(true);
								             actionBar.setDisplayHomeAsUpEnabled(true);
								               actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME
								            	        | ActionBar.DISPLAY_SHOW_TITLE | ActionBar.DISPLAY_SHOW_CUSTOM);
								            
								             actionBar.show();
								             
								         } else {
								       
								   }
								}
							}
					 	});
			 }
		 @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() {
			            	  astology.this.finish();
			}
		 @Override
			public boolean onCreateOptionsMenu(Menu menu) {
				MenuInflater menuInflater = getMenuInflater();
		        menuInflater.inflate(R.menu.main, menu);
		    
		        return super.onCreateOptionsMenu(menu);
			}
			    
			
	@Override
			public boolean onOptionsItemSelected(MenuItem item) {
				
			
				if (item.getItemId() == android.R.id.home)
				{
					Intent int_ab = new Intent(this,MainActivity.class);
		            int_ab.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		            startActivity(int_ab);
				}
		            else if (item.getItemId() ==R.id.drawer)
		            {
							  Intent int_sear = new Intent(this,MainActivity.class);
					            int_sear.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					            startActivity(int_sear);
		            }
					            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));
							           // FileInputStream file = new FileInputStream(new File("D:/new/SlidingMenu/data/astrology.findyourfate.com/files/myfile.xml"));
								           
							            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));
							           // FileInputStream file = new FileInputStream(new File("D:/new/SlidingMenu/data/astrology.findyourfate.com/files/myfile.xml"));
								           
							            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);
											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)
				  {
					 AlertDialog.Builder builder = new AlertDialog.Builder(this);
					    builder.setMessage("Are you sure  want to exit?")
					           .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();
				  }
		/*		 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, "Astrology by findyourfate.com");
				        emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,"Hi,I would like to suggest, this  Astrology by findyourfate.com App to you. \n Click this Link to Download app \"http://goo.gl/iexPxk\"\n\n Regards");
				    	startActivity(emailIntent);  
					
				 }	
				 else if (item.getItemId() == R.id.in)
				  {
					  AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(astology.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();
			}
	}
			        
	