package astrology.findyourfate.com;

import astrology.findyourfate.com.adapter.NavDrawerListAdapter;


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 com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView; 
import astrology.findyourfate.com.model.NavDrawerItem;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;

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 android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ShareActionProvider;

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public class ourservices extends Activity {
	private DrawerLayout mDrawerLayout;
	private ListView mDrawerList;
	private ActionBarDrawerToggle mDrawerToggle;
String fname="myfile.xml";
	// nav drawer title
	private CharSequence mDrawerTitle;
	// private AdView mAdview;
	 private AdLayout adView;
	// used to store app title
	private CharSequence mTitle;
	 private EasyTracker easyTracker = null;
	// slide menu items
	private String[] navMenuTitles;
	private TypedArray navMenuIcons;
	private ShareActionProvider mShareActionProvider;
	private ArrayList<NavDrawerItem> navDrawerItems;
	private NavDrawerListAdapter adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mainservices);
		//  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);
	        easyTracker = EasyTracker.getInstance(ourservices.this);
	    	
		mTitle = mDrawerTitle = getTitle();

		// load slide menu items
		navMenuTitles = getResources().getStringArray(R.array.OurServices);

		// nav drawer icons from resources
		navMenuIcons = getResources()
				.obtainTypedArray(R.array.Ourservice_icons);

		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerList = (ListView) findViewById(R.id.list_slidermenu); 

		navDrawerItems = new ArrayList<NavDrawerItem>();

		// adding nav drawer items to array
		// Home
		navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
		// Find People
		navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
		// Photos
		navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
		// Communities, Will add a counter here
		navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
		navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
		navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));
		navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(6, -1)));
		navDrawerItems.add(new NavDrawerItem(navMenuTitles[7], navMenuIcons.getResourceId(7, -1)));
		navDrawerItems.add(new NavDrawerItem(navMenuTitles[8], navMenuIcons.getResourceId(8, -1)));
		navDrawerItems.add(new NavDrawerItem(navMenuTitles[9], navMenuIcons.getResourceId(9, -1)));
		
		// Recycle the typed array
		navMenuIcons.recycle();

		mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

		// setting the nav drawer list adapter
		adapter = new NavDrawerListAdapter(getApplicationContext(),
				navDrawerItems);
		mDrawerList.setAdapter(adapter);

		// enabling action bar app icon and behaving it as toggle button
		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);
		
		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
				R.drawable.draw, //nav menu toggle icon
				R.string.app_name, // nav drawer open - description for accessibility
				R.string.app_name // nav drawer close - description for accessibility
		) {
			public void onDrawerClosed(View view) {
				getActionBar().setTitle(mTitle);
				// calling onPrepareOptionsMenu() to show action bar icons
				invalidateOptionsMenu();
			}

			public void onDrawerOpened(View drawerView) {
				getActionBar().setTitle(mDrawerTitle);
				// calling onPrepareOptionsMenu() to hide action bar icons
				invalidateOptionsMenu();
			}
		};
		mDrawerLayout.setDrawerListener(mDrawerToggle);

		if (savedInstanceState == null) {
			// on first time display view for first nav item
			displayView(0);
		}
		
		mDrawerLayout.openDrawer(mDrawerList);
		// mAdview.loadAd(new AdRequest.Builder().build());
		this.adView.loadAd(adOptions);
	}

	/**
	 * Slide menu item click listener
	 * */
	private class SlideMenuClickListener implements
			ListView.OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// display view for selected nav drawer item
			displayView(position);
		}
	}

	
	@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() {
	          	  ourservices.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 (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}
		 else 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);
											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(ourservices.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;
		}
	

	
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
		//menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
		return super.onPrepareOptionsMenu(menu);
	}

	/**
	 * Diplaying fragment view for selected nav drawer list item
	 * */
	private void displayView(int position) {
		// update the main content by replacing fragments
		 
		 Fragment fragment = null;
		switch (position) {
		case 0:
			 fragment = new homeservice();
			break;
			case 1:
			 fragment = new askquestion();
			break;
		case 2:
			fragment = new  matchmaking();
			break;
		case 3:
			fragment = new namechange();
			break;
		case 4:
			fragment = new dreamanalysis();
			break;
		case 5:
			fragment = new nadifirstpage();
			break;
		case 6:
			fragment = new natalchart();
			break;
		case 7:
			fragment = new palmreading();
			break;
		case 8:
			fragment = new compatreading();
			break;
		case 9:
			fragment = new vastu();
			break;
	default:
			break;
		}

		if (fragment != null) {
			FragmentManager fragmentManager = getFragmentManager();
			fragmentManager.beginTransaction()
					.replace(R.id.frame_container, fragment).commit();

			// update selected item and title, then close the drawer
			mDrawerList.setItemChecked(position, true);
			mDrawerList.setSelection(position);
			setTitle(navMenuTitles[position]);
			mDrawerLayout.closeDrawer(mDrawerList);
		} else {
			// error in creating fragment
			Log.e("OurServices", "Error in creating fragment");
		}
	}

	@Override
	public void setTitle(CharSequence title) {
		mTitle = title;
		getActionBar().setTitle(mTitle);
	}

	/**
	 * When using the ActionBarDrawerToggle, you must call it during
	 * onPostCreate() and onConfigurationChanged()...
	 */

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Pass any configuration change to the drawer toggls
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

}
