package scorpio.findyourfate.com;

import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

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.net.ConnectivityManager;
import android.os.Bundle;
import android.os.StrictMode;
import androidx.fragment.app.Fragment;
import androidx.fragment.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 weeklyh extends Fragment {
	

	  String stext = null;
	     WebView content; 
	     String sign=null ;
	 	 String fromdate=null;
	 	 String todate =null;
	 	 String weekmonth,weekyear;
	  	 View rootView;
	  	 TextView nextyearcontent,prevyrcontent;
	  	 String yrcontent=null;
	  	 Button daily,week,month,year;
	   String mname1 = null;
		   String month_name1=null;
	
	@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.weekly, container, false);
			  
			   String userAgent = new WebView(getActivity()).getSettings().getUserAgentString();
	    	   if (userAgent.contains("Mobile")) {
	    		   rootView = inflater.inflate(R.layout.weekly, container, false);
	    	   } 
	    	   else {
	    		   rootView = inflater.inflate(R.layout.weeklytab, 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);
	      
	        	   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);
	        	  
			  
			  daily.setBackgroundResource(R.drawable.daily1);
				week.setBackgroundResource(R.drawable.weeklypress);
				month.setBackgroundResource(R.drawable.monthly1);
				year.setBackgroundResource(R.drawable.yearly1);
				
				   nextyearcontent=(TextView) rootView.findViewById(R.id.nextyear);
	        	   prevyrcontent=(TextView)rootView.findViewById(R.id.prevyear);
	        	   
	        	   
	        
				  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); 
		            	   }
		      
		            
					Calendar calendarFirstDay = Calendar.getInstance(); 
	  	      	    Date now = new Date(); 
	  	      	    calendarFirstDay.setTime(now); 
	  	      	    calendarFirstDay.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
	  	      	    DateFormat weekFormat = new SimpleDateFormat("MM-dd-yyyy"); 
	  	      	    fromdate=weekFormat.format(calendarFirstDay.getTime()); 
	  	       	   DateFormat m = new SimpleDateFormat("MM");
	  	      	   weekmonth=m.format(calendarFirstDay.getTime());
	  	      	   DateFormat y = new SimpleDateFormat("yyyy");
	  	      	   weekyear=y.format(calendarFirstDay.getTime());  
	  	      	    Calendar cal2 = Calendar.getInstance();
	  	              cal2.setTime(calendarFirstDay.getTime());
	  	              cal2.add(Calendar.DATE, 6); 
	  	              todate=weekFormat.format(cal2.getTime());  
	  	              URL url1 = null;
	  				try {
	  					url1 = new URL("https://www.findyourfate.com/android-horoscope/weekly/"+weekyear+"/"+weekmonth+"/"+fromdate+"to"+todate+".xml");
	  				 
	  	             DocumentBuilderFactory dbf1 = DocumentBuilderFactory.newInstance();
	  	         	 DocumentBuilder db1 = null;
	  			 	db1 = dbf1.newDocumentBuilder();
	  			 	 Document doc1 = null;
	  				doc1 = db1.parse(new InputSource(url1.openStream()));
	  			 	doc1.getDocumentElement().normalize();
	  			 	NodeList nodeList1 = doc1.getElementsByTagName("item");
	  	           WebSettings webSettings1 = content.getSettings(); 
	  	   	       webSettings1.setSupportZoom(true);
	  	   	       webSettings1.setBuiltInZoomControls(true);
	  	   	       Node node1 = nodeList1.item(7);
	  		        //  content[i]=new WebView(this);
	  		     	Element elem = (Element) node1;
	  		     	NodeList contentList1 = elem.getElementsByTagName("content");
	  		   	    Element contentElement1 = (Element) contentList1.item(0);
	  		   	    contentList1 = contentElement1.getChildNodes();
	  		   	    
	  	  		  String text;
	  	  	 		// 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\">"+" Weekly Horoscope <br>"+"<b><font size=\""+2+"\">"+fromdate+" - "+todate+"</font></b></h4>"+ "<p align=\"justify\">" +"<font color=\"#000000\" size=\""+3+"\"   face=\"ms sans serif, verdana\">"+ ((Node) contentList1.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\">"+" Weekly Horoscope <br>"+"<b><font size=\""+4+"\">"+fromdate+" - "+todate+"</font></b></h2>"+ "<p align=\"justify\">" +"<font color=\"#000000\" size=\""+5+"\"   face=\"ms sans serif, verdana\">"+ ((Node) contentList1.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 Fragment();
	  						 	FragmentTransaction transaction = getFragmentManager().beginTransaction();
	  					 	transaction.replace(R.id.weeklyview, 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 Fragment();
	  						 	FragmentTransaction transaction = getFragmentManager().beginTransaction();
	  					 	transaction.replace(R.id.weeklyview, newFragment);  
	  							transaction.commit();  

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