package com.etixpert.evolution;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;
import java.util.ResourceBundle;

import org.apache.log4j.DailyRollingFileAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class CoordinateChecker {

	private static final String GOOGLE_MAPS_URL = "http://maps.google.com/maps/geo?q=#query#&output=csv";
	
	protected static Logger logger = Logger.getLogger("mainControl.coorinateChecker");
	
	public static void main(String[] args) {
	   ResourceBundle bundle = ResourceBundle.getBundle("evolution");
	   PatternLayout layout = new PatternLayout("%d{ABSOLUTE} %-p %c{2}: %m%n");
	   DailyRollingFileAppender appender = null;
	   try {
	     
		   appender = new DailyRollingFileAppender(layout, bundle.getString("cronlogpath"), "'.'yyyy-MM-dd");
	   } catch(Exception e) {//throw new ServletException(e);}
	       e.printStackTrace();
	   }
	   
	   logger.addAppender(appender);		
	   Transaction tx = null;
	   try {
	       Session session = HibernateUtil.currentSession();

	       tx = session.beginTransaction();
	       ObjectSearch os = new ObjectSearch();
	       logger.info("Retrieving addresses.");
	       List addresses = os.search(session.connection(), "select id, country_post_code, city, street from address where longitude is null");
	       tx.commit();
	       String country=null, city=null, street=null;
	       
	       //JAVÍTANIIIIIIII
	       for (int i=0; i<addresses.size(); i++) {
	    	   
	    	   try {
	    		   Thread.sleep(500);
	    		   logger.info("0");
	    		   PersistableObject po = (PersistableObject) addresses.get(i);
	    		   logger.info("1");
	    		   
	    		   country = po.getString("country_post_code", null);
	    		   city = po.getString("city", null);
	    		   street = po.getString("street", null);
	    		   
	    		   logger.info("2:" + country + ", "+city+", "+street);
	    		   
	    		   String[] coords = getCoordinates(country, city, street); 
	    		
	    		   logger.info("3: "+coords[0] + ", " + coords[1]);
	    		   
	    		   
	    		   tx = session.beginTransaction();
	    		   
	    		   PersistableObject new_ = new PersistableObject("address", "id");
	    		   new_.set("id", po.get("id"));
	    		   new_.load(session.connection());

	    		   new_.set("latitude", coords[0]);
	    		   new_.set("longitude", coords[1]);
	    		   
	    		   new_.update(session.connection());
	       
	    		   tx.commit();
	    		   
	    		   logger.info("6");
	    		   
	    		   
	    		   
	    	   } catch (Exception e) {
	    		   logger.info(e);
	    		   logger.info(e.getStackTrace()[0]);
	    		   if ("wrong".equals(e.getMessage())) {
	    			   logger.info("This address could not be retrieved: "+country+", "+city+", "+street);
	    			   continue;
	    		   }
	    		   
	    		   logger.info("Exception: "+e.getMessage());
	    		   break;
	           }
	       }
	     
	       HibernateUtil.closeSession();
	   } catch (Exception e) {
	       try {
	           logger.error("error occured",e);
	               if (tx!=null)
	                   tx.rollback();
	               HibernateUtil.closeSession();
	           } catch (Exception ex) {}
	       }
	   }
	
	private static String[] getCoordinates(String country, String city, String street) throws Exception  {
	    String[] ret = new String[2]; 
		String urlstr = "";
	     if (country != null) {
	    	 if ("D".equals(country)) country = "Germany";
	    	 else if ("A".equals(country)) country = "Austria";
	    	 else if ("E".equals(country)) country = "Spain";
	    	 
	    	 urlstr += country.trim().replace(" ", "+") + "+";
	     }
	     if (city    != null) urlstr += city   .trim().replace(" ", "+") + "+";
	     if (street  != null) urlstr += street .trim().replace(" ", "+") + "+";
	     urlstr = urlstr.substring(0, urlstr.length() - 1);
	     urlstr = URLEncoder.encode(urlstr, "UTF8");
	     
	     urlstr = GOOGLE_MAPS_URL.replaceAll("#query#", urlstr);

	     urlstr = urlstr.replaceAll("%2B", "+");
	     
	     URL url = new URL(urlstr);
	     
	     
	     
	     logger.info("URL: "+urlstr);
	     
	     URLConnection urlconn = url.openConnection();
	     BufferedReader in = new BufferedReader(
	                                new InputStreamReader(
	                                urlconn.getInputStream()));
	     String inputLine = in.readLine();
	     in.close();
	     
	     if (inputLine != null) {
	       logger.info("inputLine: "+inputLine);
	    	 String[] parts = inputLine.split(",");
	       if (!"200".equals(parts[0]))
	    	   throw new Exception("wrong");
	       
	       if (parts.length >= 4) {
	          //resx = Double.parseDouble(parts[2]);
	          //resy = Double.parseDouble(parts[3]);
	    	   ret[0] = parts[2];
	    	   ret[1] = parts[3];
	       } else throw new Exception("return value invalid: "+inputLine);
	    } else throw new Exception("inputLine is null");
	    
	    return ret;
	}
	
	
	
}
