package scorpio.findyourfate.com;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Paint;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class yearlyh extends Fragment {
 
	         String stext = null;
	         WebView content; 
	         String sign=null ;
	 	      View rootView;
	  	     TextView nextyearcontent,prevyrcontent;
	  	     String yrcontent=null;
	    	 Button daily,week,month,year;
	 
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
	
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork() .penaltyLog().build()); 
		    
			  rootView = inflater.inflate(R.layout.yearly, container, false);
			   String userAgent = new WebView(getActivity()).getSettings().getUserAgentString();
	    	   if (userAgent.contains("Mobile")) {
	    		   rootView = inflater.inflate(R.layout.yearly, container, false);
	    	   } 
	    	   else {
	    		   rootView = inflater.inflate(R.layout.yearlytab, container, false);
	    	   }
	   	  
			 	content = (WebView)rootView.findViewById(R.id.content);
	        	content.setBackgroundColor(0);
	         	  WebChromeClient webChromeClient=new WebChromeClient();
	        	  content.setWebChromeClient(webChromeClient);
	        	  content.getSettings().setBuiltInZoomControls(true);
	        	  content.getSettings().setDisplayZoomControls(false);
	      
	         	   nextyearcontent=(TextView) rootView.findViewById(R.id.nextyear);
	        	   prevyrcontent=(TextView)rootView.findViewById(R.id.prevyear);
	        	   
	        	   daily=(Button)rootView.findViewById(R.id.dailyv);
	        	   week=(Button)rootView.findViewById(R.id.weeklyv);
	        	   month=(Button)rootView.findViewById(R.id.monthlyv);
	        	   year=(Button)rootView.findViewById(R.id.yearlyv);
	         	   
	        	 //  nextyearcontent.setVisibility(View.GONE);
	        	//   prevyrcontent.setVisibility(View.GONE);
	      	  
	        	   
			     	  final ProgressDialog progressDialog = new ProgressDialog(getActivity());
			     	  progressDialog.setTitle("Please wait");
			           progressDialog.setMessage("Loading Content...");
			              progressDialog.setCancelable(true);
			           progressDialog.show();

			           content.setWebViewClient(new WebViewClient() {
			               @Override
			               public boolean shouldOverrideUrlLoading(WebView view, String url) {
			                   view.loadUrl(url);
			                   return true;
			               }

			               @Override
			               public void onPageFinished(WebView view, String url) {
			                   if (progressDialog.isShowing()) {
			                       progressDialog.dismiss();
			                   }
			               }

			               @Override
			               public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
			                   Toast.makeText(getActivity(), "Error:" + description, Toast.LENGTH_SHORT).show();

			               }
			           });
	        	   
	        	   
	        	   
	        	   ConnectivityManager conMgr = (ConnectivityManager) getActivity().getSystemService (Context.CONNECTIVITY_SERVICE);
	              	String error1;
	              	    if (conMgr.getActiveNetworkInfo() != null && conMgr.getActiveNetworkInfo().isAvailable() && conMgr.getActiveNetworkInfo().isConnected()) {
	              		   } else {
	              		  error1= "<html><head> <style type=\"text/css\">@font-face {font-family: MyFont; src: url(\"file:///android_asset/fonts/SEGOEPR.TTF\")}body { font-family: MyFont;  text-align: justify;font-size:larger; color:#000000; font-weight:bold; line-height:32px; }</style></head><body><p align=\"center\" style=\"padding-top:100px; padding-bottom:100px;\"><font  color=\"#000000\"  size=\"+2\" ><b> Unable to Download Feed <br />Check Your Data/WIFI Connection </b></font></p></body></html>";
	               		  content.loadDataWithBaseURL("file:///android_res/drawable/", error1, "text/html", "utf-8",null); 
	               	   }
	              	    
	              	    
	                 	  
	              	  final Calendar cal = Calendar.getInstance();
	             	    final int yr=cal.get(Calendar.YEAR);
	             	    final int nextyr=cal.get(Calendar.YEAR)+1;
	             	    
	             	 //check content of next year is exist or not
	           	 	 new Thread() {

       	    	        public void run() {	   
       	    	   
       	    	   
       	    	   try {
       	    	         HttpURLConnection.setFollowRedirects(false);
       	    	    
       	    	         HttpURLConnection con =  (HttpURLConnection) new URL("https://www.findyourfate.com/android-horoscope/yearly/"+nextyr+"/"+nextyr+".xml").openConnection();
       	    	         con.setRequestMethod("HEAD");
       	    	         if( (con.getResponseCode() == HttpURLConnection.HTTP_OK) ) 
       	    	         {    
       	    	        	 yrcontent="yes";
       	    	         System.out.println("FILE_EXISTS-true"+yrcontent);
       	    	      nextyearcontent.setPaintFlags(nextyearcontent.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
       	    	        nextyearcontent.setVisibility(View.VISIBLE);
      				    nextyearcontent.setText(" "+nextyr);
      				    
       	     	         }
       	    	         else 
       	    	         {
       	    	        	 yrcontent="no";
       	    	        	 System.out.println("FILE_EXISTS-false"+yrcontent);
       	    	         }
       	    	        
       	   	                     }
       	    	   catch (Exception e) {
       	               e.printStackTrace();
       	               yrcontent="no";
       	               System.out.println("FILE_EXISTS-false"+yrcontent);
       	            nextyearcontent.setVisibility(View.GONE);
 					prevyrcontent.setVisibility(View.GONE);
       	               
       	    	    }
       	                }
       	         }.start();   
       	         
       	              
	          	   	daily.setBackgroundResource(R.drawable.daily1);
					week.setBackgroundResource(R.drawable.weekly1);
					month.setBackgroundResource(R.drawable.monthly1);
					year.setBackgroundResource(R.drawable.yearlypress);
				
	 	 	 URL url3 = null;
  			try {
  				url3 = new URL("https://www.findyourfate.com/android-horoscope/yearly/"+yr+"/"+yr+".xml");
  			    DocumentBuilderFactory dbf3 = DocumentBuilderFactory.newInstance();
  	  	      	DocumentBuilder db3 = null;
  			 	db3 = dbf3.newDocumentBuilder();
  			  	 Document doc3 = null;
  			 		doc3 = db3.parse(new InputSource(url3.openStream()));
  			   	   doc3.getDocumentElement().normalize();
  	  	      	   NodeList nodeList3 = doc3.getElementsByTagName("item"); 
  	  	      	    WebSettings webSettings3 = content.getSettings(); 
  	  		       webSettings3.setSupportZoom(true);
  	  		       webSettings3.setBuiltInZoomControls(true);  
  	  			  
  	  		   Node node3 = nodeList3.item(7);
  	  		   Element yearelmt = (Element) node3;
  	           NodeList contentList3 = yearelmt.getElementsByTagName("content");
  	      	   Element contentElement3 = (Element) contentList3.item(0);
  	      	   contentList3 = contentElement3.getChildNodes();
  	      	
  	  			 	 String text = null;
  								sign = "Yearly Horoscope";
  								//   String userAgent = new WebView(getActivity()).getSettings().getUserAgentString();
  				  				   if (userAgent.contains("Mobile")) {
  				  					   text = "<html><head><style type=\"text/css\">   @font-face {font-family: MyFont;src: url('file:///android_asset/fonts/MTCORSVA.TTF')}body {font-family:MyFont;color:#290000; text-align: justify;}</style></head><body bgcolor=\"\"><h4 align=\"center\">"+" Yearly Horoscope-"+"<b><font size=\""+4+"\">"+yr+"</font></b></h4>"+ "<p align=\"justify\">" +"<font color=\"#000000\" size=\""+3+"\" face=\"ms sans serif, verdana\">"+ ((Node) contentList3.item(0)).getNodeValue()+ "</font></p> "+ "</body></html>";
  				  				   }
  				  				   else
  				  				   {
  				  					   text = "<html><head><style type=\"text/css\">   @font-face {font-family: MyFont;src: url('file:///android_asset/fonts/MTCORSVA.TTF')}body {font-family: MyFont;color:#290000; text-align: justify;}</style></head><body bgcolor=\"\"><h2 align=\"center\">"+" Yearly Horoscope-"+"<b><font size=\""+6+"\">"+yr+"</font></b></h2>"+ "<p align=\"justify\">" +"<font color=\"#000000\" size=\""+5+"\" face=\"ms sans serif, verdana\">"+ ((Node) contentList3.item(0)).getNodeValue()+ "</font></p> "+ "</body></html>";
  				   				   }
  					     	   	content.loadDataWithBaseURL("file:///android_res/drawable/",text, "text/html", "utf-8",null);  
  			 	 
  				}
  				  catch (Exception e) {
  	             	 System.out.println("XML Pasing Excpetion = " + e);
  	       	   }	
  			
  		    	nextyearcontent.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					nextyearcontent.setVisibility(View.GONE);
					 prevyrcontent.setText(" "+yr);
					 prevyrcontent.setPaintFlags(prevyrcontent.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
					 prevyrcontent.setVisibility(View.VISIBLE);
					 
					 
					  final ProgressDialog progressDialog = new ProgressDialog(getActivity());
			     	  progressDialog.setTitle("Please wait");
			           progressDialog.setMessage("Loading Content...");
			              progressDialog.setCancelable(true);
			           progressDialog.show();

			           content.setWebViewClient(new WebViewClient() {
			               @Override
			               public boolean shouldOverrideUrlLoading(WebView view, String url) {
			                   view.loadUrl(url);
			                   return true;
			               }

			               @Override
			               public void onPageFinished(WebView view, String url) {
			                   if (progressDialog.isShowing()) {
			                       progressDialog.dismiss();
			                   }
			               }

			               @Override
			               public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
			                   Toast.makeText(getActivity(), "Error:" + description, Toast.LENGTH_SHORT).show();

			               }
			           });
		
				  URL url3 = null;
			  			try {
			  				url3 = new URL("https://www.findyourfate.com/android-horoscope/yearly/"+nextyr+"/"+nextyr+".xml");
			  			    DocumentBuilderFactory dbf3 = DocumentBuilderFactory.newInstance();
			  	  	      	DocumentBuilder db3 = null;
			  			 	db3 = dbf3.newDocumentBuilder();
			  			  	 Document doc3 = null;
			  			 	doc3 = db3.parse(new InputSource(url3.openStream()));
			  			   	 doc3.getDocumentElement().normalize();
			  	  	      	  NodeList nodeList3 = doc3.getElementsByTagName("item"); 
			  	  	      	   WebSettings webSettings3 = content.getSettings(); 
			  	  		      webSettings3.setSupportZoom(true);
			  	  		      webSettings3.setBuiltInZoomControls(true);  
			  	  			  
			  	  		   Node node3 = nodeList3.item(7);
			  	  		   Element yearelmt = (Element) node3;
			  	           NodeList contentList3 = yearelmt.getElementsByTagName("content");
			  	      	   Element contentElement3 = (Element) contentList3.item(0);
			  	      	   contentList3 = contentElement3.getChildNodes();
			  	      	
			  	  			 	 String text = null;
			  								sign = "Yearly Horoscope";
			  								   String userAgent = new WebView(getActivity()).getSettings().getUserAgentString();
			  				  				   if (userAgent.contains("Mobile")) {
			  				  					   text = "<html><head><style type=\"text/css\">   @font-face {font-family: MyFont;src: url('file:///android_asset/fonts/MTCORSVA.TTF')}body {font-family: MyFont;color:#290000; text-align: justify;}</style></head><body bgcolor=\"\"><h4 align=\"center\">"+" Yearly Horoscope-"+"<b><font size=\""+4+"\">"+nextyr+"</font></b></h4>"+ "<p align=\"justify\">" +"<font color=\"#000000\" size=\""+3+"\" face=\"ms sans serif, verdana\">"+ ((Node) contentList3.item(0)).getNodeValue()+ "</font></p> "+ "</body></html>";
			  				  				   }
			  				  				   else
			  				  				   {
			  				  					   text = "<html><head><style type=\"text/css\">   @font-face {font-family: MyFont;src: url('file:///android_asset/fonts/MTCORSVA.TTF')}body {font-family: MyFont;color:#290000; text-align: justify;}</style></head><body bgcolor=\"\"><h2 align=\"center\">"+" Yearly Horoscope-"+"<b><font size=\""+6+"\">"+nextyr+"</font></b></h2>"+ "<p align=\"justify\">" +"<font color=\"#000000\" size=\""+5+"\" face=\"ms sans serif, verdana\">"+ ((Node) contentList3.item(0)).getNodeValue()+ "</font></p> "+ "</body></html>";
			  				   				   }
			  					     	   	content.loadDataWithBaseURL("file:///android_res/drawable/",text, "text/html", "utf-8",null);  
			  			 	 
			  				}
			  				  catch (Exception e) {
			  	             	 System.out.println("XML Pasing Excpetion = " + e);
			  	       	   }	
			  	
	 			}
			});
  			
  			
	prevyrcontent.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
		 			prevyrcontent.setVisibility(View.GONE);
					nextyearcontent.setVisibility(View.VISIBLE);
					
			 	 URL url3 = null;
		  			try {
		  				url3 = new URL("https://www.findyourfate.com/android-horoscope/yearly/"+yr+"/"+yr+".xml");
		  			    DocumentBuilderFactory dbf3 = DocumentBuilderFactory.newInstance();
		  	  	      	DocumentBuilder db3 = null;
		  			 	db3 = dbf3.newDocumentBuilder();
		  			  	 Document doc3 = null;
		  			 		doc3 = db3.parse(new InputSource(url3.openStream()));
		  			   	   doc3.getDocumentElement().normalize();
		  	  	      	   NodeList nodeList3 = doc3.getElementsByTagName("item"); 
		  	  	      	    WebSettings webSettings3 = content.getSettings(); 
		  	  		       webSettings3.setSupportZoom(true);
		  	  		       webSettings3.setBuiltInZoomControls(true);  
		  	  			  
		  	   		   Node node3 = nodeList3.item(7);
		  	  		   Element yearelmt = (Element) node3;
		  	           NodeList contentList3 = yearelmt.getElementsByTagName("content");
		  	      	   Element contentElement3 = (Element) contentList3.item(0);
		  	      	   contentList3 = contentElement3.getChildNodes();
		  	      	
		  	  		 String text = null;
		  								sign = "Yearly Horoscope";
		  								   String userAgent = new WebView(getActivity()).getSettings().getUserAgentString();
		  				  				   if (userAgent.contains("Mobile")) {
		  				  					   text = "<html><head><style type=\"text/css\">   @font-face {font-family: MyFont;src: url('file:///android_asset/fonts/MTCORSVA.TTF')}body {font-family: MyFont;color:#290000; text-align: justify;}</style></head><body bgcolor=\"\"><h4 align=\"center\">"+" Yearly Horoscope-"+"<b><font size=\""+4+"\">"+yr+"</font></b></h4>"+ "<p align=\"justify\">" +"<font color=\"#000000\" size=\""+3+"\" face=\"ms sans serif, verdana\">"+ ((Node) contentList3.item(0)).getNodeValue()+ "</font></p> "+ "</body></html>";
		  				  				   }
		  				  				   else
		  				  				   {
		  				  					   text = "<html><head><style type=\"text/css\">   @font-face {font-family: MyFont;src: url('file:///android_asset/fonts/MTCORSVA.TTF')}body {font-family: MyFont;color:#290000; text-align: justify;}</style></head><body bgcolor=\"\"><h2 align=\"center\">"+" Yearly Horoscope-"+"<b><font size=\""+6+"\">"+yr+"</font></b></h2>"+ "<p align=\"justify\">" +"<font color=\"#000000\" size=\""+5+"\" face=\"ms sans serif, verdana\">"+ ((Node) contentList3.item(0)).getNodeValue()+ "</font></p> "+ "</body></html>";
		  				   				   }
		  					     	   	content.loadDataWithBaseURL("file:///android_res/drawable/",text, "text/html", "utf-8",null);  
		  			 	 
		  				}
		  				  catch (Exception e) {
		  	             	 System.out.println("XML Pasing Excpetion = " + e);
		  	       	   }	
				}
			});
  			
	 daily.setOnClickListener(new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			 daily.setClickable(false);
			  Fragment newFragment = new horoscope();  
			 	FragmentTransaction transaction = getFragmentManager().beginTransaction();
		 	transaction.replace(R.id.yearlyview, newFragment);  
				transaction.commit();  

		}
	});
	
	month.setOnClickListener(new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			 month.setClickable(false);
			  Fragment newFragment = new monthlyh();  
			 	FragmentTransaction transaction = getFragmentManager().beginTransaction();
		 	transaction.replace(R.id.yearlyview, newFragment);  
				transaction.commit();  

		}
	});
 
 week.setOnClickListener(new View.OnClickListener() {
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		 week.setClickable(false);
		  Fragment newFragment = new weeklyh();  
		 	FragmentTransaction transaction = getFragmentManager().beginTransaction();
	 	transaction.replace(R.id.yearlyview, newFragment);  
			transaction.commit();  
	}
});
	
	
	        	  
	        	  
			  
			  return rootView;
	}

}
