'use strict';
var models = require("../models/models.js");
var request = require('request');
const ForecastIO = require('forecast-io');
const forecast = new ForecastIO('a1eae5b3ea234b0ea5dcbcccaa72195c');
const LAT_BSAS = '-34.605664';
const LON_BSAS = '-58.498754';


/*
var options = {
    units: "ca",
    exclude: ['minutely, daily, alerts, flags'],
    extend: "hourly"
};

var weatherman = require( "weatherman.io" );
var alRoker = new weatherman('a1eae5b3ea234b0ea5dcbcccaa72195c');
*/

const LAT = '38.599932';
const LON = '-0.046696';

exports.init = function(){
	setInterval(checkSP, 30000);
	//setTimeout(checkSP, 5000);
	console.log("setTimeout...");
}

function checkSP() {
  console.log("Pasó el tiempo...");

	var d = new Date();
	var ahora = d.getTime(); 

	console.log("Pasó el tiempo..." + ahora);

	var spagers = models.Sportpagers;
	var dataQuery = {
			where: {fechaAviso: {$lte: ahora}, tipo: "enviar"}
	};

	spagers.count(dataQuery)
	.then(function(cant) {
		console.log("fechaAviso pasada Encontrados:" + cant);

		if(cant > 0){

			spagers.findAll(dataQuery).then(function(usuarios){
				for(var i=0; i< cant; i++){
					//console.log("fechaAviso findAll:" + usuarios[i].fechaAviso);
					checkForecast(usuarios[i]);
				}
			});

		}

	});
}

function checkForecast(sp) {	

	var lat = parseFloat(sp.latitud);
	var lon = parseFloat(sp.longitud);
	//lat = LAT_BSAS;
	//lon = LON_BSAS;

	//var date = new Date(sp.fechaPronostico);
	var fecha = timeConverter(sp.fechaPronostico);
	console.log("Entrando en Forecast at: ---> " + fecha);
	console.log("Entrando en Forecast: " + lat);
	console.log("Entrando en Forecast: " + sp.firebase_id);

	forecast
	    .latitude(sp.latitud)            //\\ required: latitude, string.
	    .longitude(sp.longitud)          //\\ required: longitude, string.
	    .time(fecha)             // optional: date, string 'YYYY-MM-DD'.
	    .units('ca')                    //\\ optional: units, string, refer to API documentation.
	    .language('es')                 //\\ optional: language, string, refer to API documentation.
	    .exclude('minutely, hourly, daily, alerts, flags')     // \\ optional: exclude, string, refer to API documentation.
	    //.exclude('minutely, daily, alerts, flags')     // \\ optional: exclude, string, refer to API documentation.
	    //.extendHourly(true)             \\ optional: extend, boolean, refer to API documentation.
	    .get()                          //\\ execute your get request.
	    .then(function(pronostico) {

	    	var jsonfc = JSON.parse(pronostico);

	        //console.log("pronóstico OK: " + pronostico);
	        //console.log("Esperanza: " + JSON.stringify(sp));

	        if(verificarSiCumpleCondiciones(sp, jsonfc) === true){
		        jsonfc.condiciones = "OK";
		        console.log("Condiciones OK");
				notificarSportPager(sp, "Sport Pager: buenas condiciones");

	        }else{
		        jsonfc.condiciones = "Desfavorables";
		        console.log("Pronóstico: condiciones desfavorables");
				notificarSportPager(sp, "Sport Pager: condiciones desfavorables");
	        }

		})
	    .catch(function(error) {
	        console.log("Falla: " + error);
	        //console.log(err);
		});

}

function verificarSiCumpleCondiciones(sp, pronostico){

	var ret = true;

	var dirVientoMin = parseInt(getDirVientoMin(sp));
	var dirVientoMax = parseInt(getDirVientoMax(sp));

	/*
	var tipo = typeof (pronostico.currently.temperature);
	console.log("typeof pronostico.temperature: " + tipo);
	tipo = typeof (pronostico.currently.windSpeed);
	console.log("typeof pronostico.windSpeed: " + tipo);
	tipo = typeof (pronostico.currently.windBearing);
	console.log("typeof pronostico.windBearing: " + tipo);
	tipo = typeof (dirVientoMax);
	console.log("typeof dirVientoMax: " + tipo);
	*/
	
	if(pronostico.currently.hasOwnProperty("temperature")){
		if(pronostico.currently.temperature < sp.tempMin){ret = false;}else{
			console.log("tempMin OK");
		}
		if(pronostico.currently.temperature > sp.tempMax){ret = false;}else{
			console.log("tempMax OK");
		}
	};
	if(pronostico.currently.hasOwnProperty("windSpeed")){
		if(pronostico.currently.windSpeed < sp.velVientoMin){ret = false;}else{
			console.log("velVientoMin OK");
		}
		if(pronostico.currently.windSpeed > sp.velVientoMax){ret = false;}else{
			console.log("velVientoMax OK");
		}
	};
	if(pronostico.currently.hasOwnProperty("windBearing")){
		if(pronostico.currently.windBearing < dirVientoMin){ret = false;}else{
			console.log("dirVientoMin OK");
		}
		if(pronostico.currently.windBearing > dirVientoMax){ret = false;}else{
			console.log("dirVientoMax OK");
		}
	};
	if(pronostico.currently.hasOwnProperty("precipProbability")){
		if(pronostico.currently.precipProbability < sp.probLluviaMin){ret = false;}else{
			console.log("probLluviaMin OK");
		}
		if(pronostico.currently.windprecipProbabilityBearing > sp.probLluviaMax){ret = false;}else{
			console.log("probLluviaMax OK");
		}
	};

	if(pronostico.currently.hasOwnProperty("summary")){
		if((sp.sinNubes === 1) && (sp.ParcialmenteNublado === 1) && (sp.Nublado === 1)) {} else{
			if((sp.sinNubes === 0) && (sp.ParcialmenteNublado === 0) && (sp.Nublado === 0)) {} else{
				if(sp.sinNubes === 1){
					if(pronostico.currently.summary.toLowerCase().search("nublado") > 0 ){
						ret = false;
					}else{
						console.log("sin nubes OK");
					}
				}
				if(sp.ParcialmenteNublado === 1){
					if(pronostico.currently.summary.toLowerCase() !== "parcialmente nublado"){
						ret = false;
					}else{
						console.log("parcialmente nublado OK");
					}
				}
				if(sp.Nublado === 1){
					if(pronostico.currently.summary.toLowerCase() !== "nublado"){
						ret = false;
					}else{
						console.log("nublado OK");
					}
				}
			}
		}
	};

	return ret;
}

function getDirVientoMax(sp){

	var dir = sp.dirViento;
	var n = dir.search(";");
	n++;
	var dirMax = dir.substr(n);
	console.log("dirMax: " + dirMax);
	return dirMax;
}

function getDirVientoMin(sp){

	var remplazo = ";" + getDirVientoMax(sp);
	var dir = sp.dirViento;
	var dirMin = dir.replace(remplazo, ""); 
	console.log("dirMin: " + dirMin);
	return dirMin;
}


function timeConverter(UNIX_timestamp){ // '2016-09-28 06:00'
	/*
	var d = new Date()
	var n = d.getTimezoneOffset();

	console.log("Timezone: " + n);

	UNIX_timestamp += (n*60000);
	*/

	var a = new Date(UNIX_timestamp);
	var months = ['01','02','03','04','05','06','07','08','09','10','11','12'];
	var year = a.getFullYear();
	var month = months[a.getMonth()];
	var date = "" + a.getDate();
	var hour = "" + a.getHours();
	var min = "" + a.getMinutes();
	var sec = "" + a.getSeconds();

	if(date.length === 1){ date = "0" + date};
	if(hour.length === 1){ hour = "0" + hour};
	if(min.length === 1){ min = "0" + min};
	//if(sec.length === 1){ sec = "0" + sec};

	//var time = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min + ':' + sec ;
	var time = year + "-" + month + "-" + date + " " + hour + ":" + min + ":00";
	return time;
}


function notificarSportPager(sp, resultado)
{
	var d = new Date();
	var ahora = "" + d.getTime(); 
	console.log("notificarSportPager");

	var datos = {
		"data" : {
			"rowId": sp.rowId,
			"firebase_id": sp.firebase_id,
			"body" : "para " + sp.fechaPronosticoString + ", "+ sp.lugar,
			"title" : resultado,
			"icon" : "notificacion_sp",
			"sound": "defaultSoundUri",
			"ticker": "Sport Pager"
		},
		"to" : sp.firebase_id
		//"collapse_key" : ahora
	};	

	var post_options = {
		url: 'https://fcm.googleapis.com/fcm/send',
		method: 'POST',
		json: true,
		headers: {
			'Content-Type': 'application/json',
			'Authorization': 'key=AIzaSyDSjS3_iWi7rwJdf4CxX0Kl4yC-mOD2Z4M',
		},
		body: datos
	};

	function callback(error, response, body) {

		if (!error && response.statusCode == 200) { 

			console.log("Notifications OK!: " + response.statusMessage + " " + JSON.stringify(body));
			
			if(body.success === 1)
			{
				notificacionEnviadaOK(sp.firebase_id, sp.rowId);
			}
		}
		else {
			console.log("Falló notifications: " + error + " " + response + " " + JSON.stringify(body));
		}
	}

	request(post_options, callback);
}


/*
function notificarSportPager1(sp, resultado)
{
	var d = new Date();
	var ahora = "" + d.getTime(); 


	var datos = {
		"collapse_key" : ahora,
		"data": {
			rowId: sp.rowId,
			firebase_id: sp.firebase_id
		},
		//"to" : "cyytAyfUj2A:APA91bFJKe1DUajyuisS_hDKQo1WlTGiEbTuW-9mLRbK8Iv9AfWheWevkefOV57-HBbEE89_C1SRWZY6S10L8gcv-z2PQz6AqaD7kpM4_j3OCaVfKiUabEHMLCVT74_fOIBsthykSG2A",
		"to" : sp.firebase_id,
		"notification" : {
			"body" : "para " + sp.fechaPronosticoString + ", "+ sp.lugar,
			"title" : resultado,
			"icon" : "notificacion_sp",
			"sound": "defaultSoundUri",
			"ticker": "Sport Pager"
		}
	};	

	var post_options = {
		url: 'https://fcm.googleapis.com/fcm/send',
		method: 'POST',
		json: true,
		headers: {
			'Content-Type': 'application/json',
			'Authorization': 'key=AIzaSyDSjS3_iWi7rwJdf4CxX0Kl4yC-mOD2Z4M',
		},
		body: datos
	};

	function callback(error, response, body) {

		if (!error && response.statusCode == 200) { 

			console.log("Notifications OK!: " + response.statusMessage + " " + JSON.stringify(body));
			
			if(body.success === 1)
			{
				notificacionEnviadaOK(sp.firebase_id, sp.rowId);
			}
		}
		else {
			console.log("Falló notifications: " + error + " " + response + " " + JSON.stringify(body));
		}
	}

	request(post_options, callback);
}
*/

function notificacionEnviadaOK(firebase_id, rowId){

	var sportpagers = models.Sportpagers;

	var dataQuery = {tipo: "enviado"};
	var dataWhere = {where: {firebase_id: firebase_id, rowId: rowId}};

	sportpagers 
	.update(dataQuery, dataWhere)
	.then( function(affectedRows){
	console.log("Sportpager ACK. rows: " + affectedRows);
	});
}


