package app.world;

import java.io.StringWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.heroku.sdk.jdbc.DatabaseUrl;

import app.recorrida.RecorridaController;
import app.util.Path;
import app.util.StandardResponse;
import app.util.ViewUtil;
import app.util.StandardResponse.StatusResponse;
import spark.ModelAndView;
import spark.Request;
import spark.Response;
import spark.Route;
import spark.TemplateViewRoute;
import utils.DAH;

public class WorldControler {
	private static final Logger logger = LoggerFactory.getLogger(RecorridaController.class);
	
	/**
	 * metodo que devuelve en formato json los nombres de las recorridas disponibles
	 */
	public static Route getWorld =  (Request request, Response response) -> {
        Map<String, Object> model = new HashMap<>();
       // model.put("users", userDao.getAllUserNames());
        //model.put("events", "algunos eventos");
        model.put("title","algun evento");
     
        
        //model.put("users",getEvents() );
       // FreeMarkerEngine fm= new FreeMarkerEngine();
      //  return fm.render(new ModelAndView(model, "index.ftl"));
       // model.put("book", bookDao.getRandomBook());
       
      return ViewUtil.render(request, model,  Path.Template.WORLD);
	};
	
	public static TemplateViewRoute getLastPoligon =  (Request request, Response response) -> {
		
		Connection connection = null;
		Map<String, Object> attributes = new HashMap<>();
		try {
			connection = DatabaseUrl.extract().getConnection();
			Statement stmt = connection.createStatement();
			//stmt.executeUpdate("CREATE TABLE IF NOT EXISTS sessiones (tick timestamp, version varchar(255))");
			
			SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");//.format(myTimestamp);
			
			//ResultSet countRS = stmt.executeQuery("SELECT COUNT(*) FROM sessiones");
			 //countRS.next();
			 //int size = countRS.getInt(1);
			 
			 /*
			  * tick timestamp with time zone NOT NULL DEFAULT now(),
			"begin" character varying(255) ,
			"end" character varying(255) ,
			"paths" character varying(10000) ,
			"token" character varying(255) ,
			  */
			ResultSet rs = stmt.executeQuery("SELECT \"tick\", \"begin\", \"end\", \"paths\", \"token\" FROM requests ORDER BY tick DESC");
			ArrayList<String> output = new ArrayList<String>();
			
			Timestamp tick = null;
			int millisIn3H = 3*60*60*1000;//hago el cambio horario para la argentina
			while (rs.next()) {				
				tick = rs.getTimestamp("tick");
				tick.setTime(tick.getTime()-millisIn3H);
				
				JsonObject json = new JsonObject();
				json.addProperty("tick", df.format(tick));
				json.addProperty("begin", rs.getString("begin"));
				json.addProperty("end", rs.getString("end"));
				json.addProperty("paths", rs.getString("paths"));
				json.addProperty("token", rs.getString("token"));
				
				
			      
			      
			      
				output.add(new Gson().toJson(json));
//				output.add( df.format(tick)+",\t"+
//				rs.getString("begin")+",\t"+
//				rs.getString("end")+",\t"+
//				rs.getString("paths")+",\t"+
//				rs.getString("token")
//				);
				
			}
			attributes.put("message", "tick\t"+"begin\t"+"end\t"+"paths\t"+"token");
			attributes.put("results", output);
			return new ModelAndView(attributes, "json.ftl");
		} catch (Exception e) {
			attributes.put("message", "There was an error: " + e);
			e.printStackTrace();
			return new ModelAndView(attributes, "error.ftl");
		} finally {
			if (connection != null) try{connection.close();} catch(SQLException e){}
		}
	};
}

@@ -2640,16 +2640,26 @@
 ick DESC
+ limit 100
 %22);%0D%0A%09%09%09

requests query 1