import { Component } from '@angular/core';
import { NavController, NavParams, LoadingController, AlertController } from 'ionic-angular';
import { GoogleAnalytics } from 'ionic-native';
import { BarcodeScanner } from '@ionic-native/barcode-scanner';
import { Lipigas } from '../../lipigas';
import { Http, Headers, RequestOptions } from '@angular/http';
import { Network } from '@ionic-native/network';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/forkJoin';
import { of } from 'rxjs/observable/of';
import * as global from '../../global';
import { Sub }  from '../../pages/cursos/sub';
import { Storage } from '@ionic/storage';

declare var cordova:any 
declare var cloudSky:any 
declare var yo: any;

@Component({
  selector: 'enrolar',
  templateUrl: 'enrolar.html',
  providers: [Lipigas, Network]
})

export class Enrolar {
  public perfil: any;
  public meses: any;
  public loading: any;
  public pendientes: any[] = [];
  public primaryTab: boolean = true;
  public secondTab: boolean = false;
  public totalPendientes: number = 0;
  public totalHistoricos: number = 0;
  public modoSinConexion: boolean = false;
  public loaded: boolean = false;
  public promises: any[] = [];
  public promises2: any[] = [];
  public promises3: any[] = [];
  public checker: any[] = [];
  public intervalo: any = null;
  public enrollActivo: any = null;
  public dif: number = 0;
  constructor(public navCtrl: NavController, private network: Network, private barcodeScanner: BarcodeScanner, private alertCtrl: AlertController, public http: Http, private service: Lipigas, public loadingController: LoadingController, public params: NavParams, private storage: Storage) {  
    this.perfil = JSON.parse(localStorage.getItem("LipigasPersonas"));
    this.meses = ['','ENE','FEB','MAR','ABR','MAY','JUN','JUL','AGO','SEP','OCT','NOV','DIC'];
    GoogleAnalytics.trackView("Listado de enrolar");
    this.dif = new Date().getTimezoneOffset();
    this.dif = (this.dif > 0 ? (this.dif / 60) : 0);
    if (navigator.onLine == false) {
      this.modoSinConexion = true;
    }
    else {
      this.modoSinConexion = false;
    }

    this.intervalo = setInterval(() => {
      if (navigator.onLine == false) {
        this.modoSinConexion = true;
      }
      else {
        this.modoSinConexion = false;
      }
    }, 1000);

    this.getCursos();
  }

  ngOnInit() {
     yo = this;
  }
  ngOnDestroy() {
    if (this.intervalo) {
      clearInterval(this.intervalo);
    }
  }

  public getCursos() {
    
    this.loading = this.loadingController.create({content:'cargando...'});
    this.loading.present();
    
    if (navigator.onLine == false) {
      this.processEnrolarUpdate(null,'err')
    }
    else {
      var fd = new Date();
      console.log("Get information cursos from source");
      console.log(fd);

      this.http.get(global.api+'/cursos/enrolar/listado', this.headers())
      .map(res => res.json())
      .subscribe(
        data => this.processEnrolarUpdate(data,'ok'),
        err => this.processEnrolarUpdate(err,'err')
      );
    } 
  }

  public processEnrolarUpdate(obj: any, res: string) {
    if (obj != null && res == 'ok') {
      this.storage.set("cursos", obj.resultado).then((value) => {
        this.populate();
      }).catch(() => {
        this.populate();
      });
    }
    else {
      this.populate();
    }
  }

  public populate() {
    this.storage.get("cursos").then((cursos_array) => {

      var runobservable = 0;
      this.pendientes = cursos_array;

      for (var i = 0;i < this.pendientes.length;i++) {
        
      	// calculo variable
        this.pendientes[i].fecha_inicio = this.formatDate(this.pendientes[i].fecha_inicio)+".000-0"+this.dif+":00";
        this.pendientes[i].fecha_termino = this.formatDate(this.pendientes[i].fecha_termino)+".000-0"+this.dif+":00";
        this.pendientes[i].pasado = 0;
        this.pendientes[i].show = 0;
        this.pendientes[i].disponible = 0;
        this.pendientes[i].hh_ini = '';
        this.pendientes[i].tipo = '';
        this.pendientes[i].activoTipo = '';
        this.pendientes[i].activoID = 0;

        // sub nodo
        if (!this.pendientes[i].hasOwnProperty("modulos")) {
        	this.pendientes[i].modulos = [];
        }

        if (navigator.onLine == true) {
          runobservable = 1;
          this.promises.push(this.http.get(global.api+'/cursos/enrolar/'+this.pendientes[i].id+'/listado', this.headers()).map(res => res.json()));
        }
        //console.log(this.pendientes[i]);
      }

      if (runobservable == 1) {
        
        Observable.forkJoin(this.promises).subscribe(res => {
          let forkJoinIndex = 0;
          for (var x = 0; x < res.length; x++) {
            this.promises2.push(this.populateModules(forkJoinIndex,res[x]));
            forkJoinIndex++;
          }
          

          Observable.forkJoin(this.promises2).subscribe(reply => {
            this.storage.set("cursos", this.pendientes).then((value) => {
              this.als();
            });
          });
          
        });
      }
      else {
        this.als();
      }
    });
  }

  public als() {
  	if (navigator.onLine == true) {
	  for (var i = 0;i < this.pendientes.length;i++) {
	    for (var j = 0; j < this.pendientes[i].modulos.length; j++) {
	      var landa = this.http.get(global.api+'/cursos/enrolar/'+this.pendientes[i].modulos[j].id+'/'+this.pendientes[i].modulos[j].tipo+'/alumnos', this.headers()).map(res => res.json());
	      this.promises3.push(landa);
	      var backup = {
	      	id: this.pendientes[i].modulos[j].id,
	      	tipo: this.pendientes[i].modulos[j].tipo
	      };
	      this.checker.push(backup);
	    }
	  }
      Observable.forkJoin(this.promises3).subscribe(reply => {
      	for (var i=0;i<reply.length;i++) {
	      this.populateAls(this.checker[i].id, this.checker[i].tipo, reply[i]);
      	}
        this.calculateInstances();
      });
  	}
  	else {
  	  this.calculateInstances();
  	}
  }

  public populateAls(id: number, tipo: string, obj: any) {

  	this.storage.get("als_"+id+"_"+tipo).then((x) => {
  	  if (x == null) {
  	  	for (var u = 0; u < obj.resultado.length ; u++ ) {
  	  		if (obj.resultado[u].estado == 1) {
  	  			obj.resultado[u].sync = 1;
  	  		}
  	  		else {
  	  			obj.resultado[u].sync = 0;
  	  		}

  	  		obj.resultado[u].fecha = '';
  	  		obj.resultado[u].motivo = '';
  	  		obj.resultado[u].offline = 1;
  	  		obj.resultado[u].metodo = '';
  	  		obj.resultado[u].latitud = '';
  	  		obj.resultado[u].longitud = '';
  	  		obj.resultado[u].mdl_tipo = tipo;
  	  		obj.resultado[u].mdl_id = id;
  	  	}

  	  	this.storage.set("als_"+id+"_"+tipo, obj.resultado);
  	  }
  	  else {
  	  	// evaluate

  	  }
  	});
  }

  public populateModules(indexCurso: number, modules: any) {
    if (modules.resultado != null) {
      modules = modules.resultado;
      for (var j = 0; j < modules.length ; j++ ) {
        modules[j].fecha = this.formatDate(modules[j].fecha)+".000-0"+this.dif+":00";
        this.pendientes[indexCurso].modulos = modules;
      }
    }
    return Observable.of(() => { });
  }

  public calculateInstances() {

    var ahora = new Date();

    for (var i = 0; i < this.pendientes.length; i++) {

      var tramoDisponible = 0;
      var refDate = new Date("2050-01-01T00:00:00.000-0"+this.dif+":00");
      for (var j = 0; j < this.pendientes[i].modulos.length ; j++ ) {


        console.log("checking", this.pendientes[i].modulos[j]);

        var margen = 0;
        var original = new Date(this.formatDate(this.pendientes[i].modulos[j].fecha));
        var x = new Date();
        var y = new Date();
        console.log("original: ", original);
      
        if (this.pendientes[i].modulos[j].hasOwnProperty("rango_inicio") && this.pendientes[i].modulos[j].rango_inicio != null) {
          margen = this.pendientes[i].modulos[j].rango_inicio; 
          if (isNaN(margen)) { margen = 0; }
          console.log("x = original - ", margen);
          x.setTime(original.getTime() - (margen * 60000));
        }
        else {
          x.setTime(original.getTime());
        }

        if (this.pendientes[i].modulos[j].hasOwnProperty("rango_termino") && this.pendientes[i].modulos[j].rango_termino != null) {
          margen = this.pendientes[i].modulos[j].rango_termino; 
          if (isNaN(margen)) { margen = 0; }
          console.log("y = original + ", margen);
          y.setTime(original.getTime() + (margen * 60000));
        }
        else {
          y.setTime(original.getTime());
        }

        
        console.log("x: ", x);
        console.log("y: ", y);
        console.log("ahora: ", ahora);

        if (ahora.getTime() <= x.getTime() && tramoDisponible == 0) {  
          this.pendientes[i].fecha_inicio = this.formatDate(  x.getFullYear() + 
                                                              '-' +
                                                              ((x.getMonth()+1) < 10 ? '0'+(x.getMonth()+1) : (x.getMonth()+1) ) + 
                                                              '-' + 
                                                              (x.getDate() < 10 ? '0'+x.getDate() : x.getDate() ) +
                                                              ' ' + (x.getHours() < 10 ? '0'+x.getHours() : x.getHours()) + ':' + (x.getMinutes() < 10 ? '0'+x.getMinutes() : x.getMinutes()) + 
                                                              ':00.000-0'+this.dif+':00');
          this.pendientes[i].hh_ini = (x.getHours() < 10 ? '0'+x.getHours() : x.getHours()) + ':' + (x.getMinutes() < 10 ? '0'+x.getMinutes() : x.getMinutes());
          console.log("Resultado: FUTURO");
          tramoDisponible = 1;                
          this.totalPendientes++;
          refDate = x;
        }

        else if (ahora.getTime() >= x.getTime() && ahora.getTime() <= y.getTime() && tramoDisponible == 0) {
          this.pendientes[i].disponible = 1;
          this.pendientes[i].tipo = this.pendientes[i].modulos[j].tipo;
          this.pendientes[i].activoTipo = this.pendientes[i].modulos[j].tipo;
          this.pendientes[i].activoID = this.pendientes[i].modulos[j].id;
          tramoDisponible = 1;
          this.totalPendientes++;
          refDate = x;
        }
        else {
          console.log("Resultado: PASADO");
        }

        console.log("****************************");
      }
      if (tramoDisponible == 0) { // ningun tramo disponible
        this.totalHistoricos++;
        this.pendientes[i].pasado = 1;
      }
    }
    this.loaded = true;
    this.loading.dismiss();
  }

  public openEnrolar(obj: any) {
    this.navCtrl.push(Sub, { element: obj });
  }

  public procesaRut(rut: string, metodo: string) {
  	var t = this.enrollActivo.activoTipo;
  	var i = this.enrollActivo.activoID;

  	this.storage.get("als_"+i+"_"+t).then((x) => {
  		
		var d = new Date(),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear(),
        hh = '' + d.getHours(),
        mm = '' + d.getMinutes();

    	if (month.length < 2) month = '0' + month;
    	if (day.length < 2) day = '0' + day;
    	if (hh.length < 2) hh = '0' + hh;
    	if (mm.length < 2) mm = '0' + mm;

     	var fff = [year, month, day].join('-');
     	fff = fff + 'T' + hh + ':' + mm;
  		var f=0;
  		var found=null;
  		for (var z = 0; z < x.length ; z++) {
  			found = x[z];
  			if (x[z].rut == rut) {
  				x[z].estado = 1;
  				x[z].fecha = fff;
  				x[z].metodo = metodo;
  				x[z].latitud = '';
  				x[z].longitud = '';
  				x[z].sync = 0;
	  	  		x[z].mdl_id = i;
	  	  		x[z].mdl_tipo = t;
  				f = 1;
  			}
  		}
  		if (f == 0) {
  			var o = {
  				rut: rut,
	  	  		sync: 0,
	  	  		estado: 1,
	  	  		fecha: fff,
	  	  		motivo: '',
	  	  		offline: 1,
	  	  		metodo: metodo,
	  	  		latitud: '',
	  	  		longitud: '',
	  	  		mdl_id: i,
	  	  		mdl_tipo: t
  			};
  			x.push(o);
  			this.service.showMsg("RUT "+rut+" ingresado con éxito");
  		}
  		else {
  			if (found.estado == 1) {
  				this.service.showMsg("RUT "+rut+" ya está presente");
  			}
  			else {
  				this.service.showMsg("RUT "+rut+" ingresado con éxito");
  			}
  		}
  		this.storage.set("als_"+i+"_"+t, x);
  	});
  }
  public enrolate(obj: any) {
  	this.enrollActivo = obj;

     cordova.plugins.barcodeScanner.scan(
        function (result) {
          if (result.cancelled == 1) {

          }
          else {
            if (result.format == "QR_CODE") {
              var rutLeido = result.text.split("?RUN=");
              if (rutLeido[1]) {
                var amp = rutLeido[1].split("&");
                var rutLeido3 = amp[0].toString();
                
                if (rutLeido3.length > 5) {
                  yo.procesaRut(rutLeido3, 'qr');
                }
                else {
                  yo.service.logError(null, "El elemento escaneado no es una cédula válida (err. 433)");
                }
              }
              else if (yo.rut(result.text)) {
                yo.procesaRut(result.text, 'qr');
              }
              else {
                yo.service.logError(null, "El elemento escaneado no es una cédula válida (err. 431)");
              }
            }
            else {
              if (result.text.length > 19) {
                var allrut = result.text.substring(0,9);
                var x_dv = allrut.substring(allrut.length - 1);
                var x_rut = allrut.substring(0,(allrut.length-1));

                var rutLeido2 = x_rut+'-'+x_dv; 
                yo.procesaRut(rutLeido2, 'pdf417');
              }
              else {
                yo.service.logError(null, "El elemento escaneado no es una cédula válida (err. 417)");
              }
            }
          }
        },
        function (error) {
            yo.service.logError(null, "Camara bloqueada por otra aplicación");
        },
        {
            preferFrontCamera : false, // iOS and Android
            showFlipCameraButton : true, // iOS and Android
            showTorchButton : true, // iOS and Android
            torchOn: false, // Android, launch with the torch switched on (if available)
            prompt : "El código debe quedar dentro de la zona demarcada", // Android
            resultDisplayDuration: 0, // Android, display scanned text for X ms. 0 suppresses it entirely, default 1500
            formats : "QR_CODE,PDF_417,EAN_8,EAN_13,CODE_128,CODE_39,CODE_93", // default: all but PDF_417 and RSS_EXPANDED
            //orientation : "portrait", // Android only (portrait|landscape), default unset so it rotates with the device
            disableAnimations : true, // iOS
            disableSuccessBeep: false // iOS
        }
      );


      /*
    this.barcodeScanner.scan({
      formats: "QR_CODE,PDF_417,PDF417", 
      prompt: "Ubica el código QR o de cédula antigua en el espacio central",
      showTorchButton: true
    }).then((barcodeData) => {
     //barcodeData
     // url qr https://portal.sidiv.registrocivil.cl/usuarios-portal/pages/DocumentRequestStatus.xhtml?RUN=16624648-2&type=CEDULA&serial=105711008
     if (barcodeData.format == 'QR_CODE') {
        var rutLeido = barcodeData.text.split("?RUN=");
        if (rutLeido[1]) {
          var amp = rutLeido[1].split("&");
          var rutLeido3 = amp[0].toString();
          
          if (rutLeido3.length > 5) {
            this.procesaRut(rutLeido3, 'qr');
          }
          else {
            this.service.logError(null, "El elemento escaneado no es una cédula válida (err. 433)");
          }
        }
        else {
          this.service.logError(null, "El elemento escaneado no es una cédula válida (err. 433)");
        }
     }
     else {
      if (barcodeData.text.length > 19) {
        var allrut = barcodeData.text.substring(0,9);
        var x_dv = allrut.substring(allrut.length - 1);
        var x_rut = allrut.substring(0,(allrut.length-1));

        var rutLeido2 = x_rut+'-'+x_dv; 
        this.procesaRut(rutLeido2, 'pdf417');
      }
      else {
        this.service.logError(null, "El elemento escaneado no es una cédula válida (err. 417)");
      }
     }


    }, (err) => {
      console.log(err);
    });
    

    cloudSky.zBar.scan(
    {
        text_title: "Lipigas Scan", 
        text_instructions: "Ubica el QR o el codigo de la cedula dentro del cuadro", 
        camera: "back",
        flash: "auto",
        drawSight: true
    }, function(s) {
      this.service.logError(null, "lectura OK: "+s);
    }, function(s) {
      this.service.logError(null, "Error de lectura: "+s);
    }
    );
    */
  }

  /* *************************** */
  /*        Alternar tabs        */
  /* *************************** */ 

  togglePendientes() {
    this.secondTab = false;
    this.primaryTab = true;
  }

  toggleHistorial() {
    this.secondTab = true;
    this.primaryTab = false;
  }
  public rut(valor: string) {
      var valor = valor.replace('.','');
      valor = valor.replace('.','');
      valor = valor.replace('-','');
      valor = valor.replace('-','');
      console.log(valor);

      var cuerpo = valor.slice(0,-1);
      var dv = valor.slice(-1).toUpperCase();
      
      if(cuerpo.length < 7) { return false;}
      
      var suma = 0;
      var multiplo = 2;
      
      for(var i=1;i<=cuerpo.length;i++) {
        var index = multiplo * parseInt(valor.charAt(cuerpo.length - i));
        suma = suma + index;
        if(multiplo < 7) { multiplo = multiplo + 1; } else { multiplo = 2; }
      }
      
      var dvEsperado = 11 - (suma % 11);
      
      dv = (dv == 'K') ? '10':dv;
      dv = (dv == '0') ? '11':dv;
      
      if(dvEsperado != parseInt(dv)) { return false; }

      return true;
  }

  /*
  public processPostSolicitar(obj: any, res: string, i: number) {
    this.loading.dismiss();
    if (res == 'ok') {
      if (obj[0].Mensaje.indexOf("solicitado") >= 0) { 
        this.closeConfirm();
        //this.beneficios[i].solicitado = 1;
                
        let conf = this.alertCtrl.create({
        title: '',
          message: obj[0].Mensaje,
          buttons: [
            {
              text: 'OK',
              role: 'cancel',
              handler: () => {
                
              }
            }
          ]
        });
        conf.present();

        //this.IDLipiSetup = 0;
        //this.IDLipipuntos = 0;
      }
      else {

        let conf = this.alertCtrl.create({
        title: 'Error',
          message: obj[0].Mensaje,
          buttons: [
            {
              text: 'OK',
              role: 'cancel',
              handler: () => {
                
              }
            }
          ]
        });
        conf.present();

      }
    }
    else {
        let conf = this.alertCtrl.create({
        title: 'Error',
          message: 'No fue posible enviar la solicitud. Intente más tarde',
          buttons: [
            {
              text: 'OK',
              role: 'cancel',
              handler: () => {
                
              }
            }
          ]
        });
        conf.present();
    }

  }
  */


  /* *********************** */
  /*    Metodos genericos    */
  /* *********************** */

  public addCommas(nStr: string) {
      nStr += '';
      var x = nStr.split('.');
      var x1 = x[0];
      var x2 = x.length > 1 ? ',' + x[1] : '';
      var rgx = /(\d+)(\d{3})/;
      while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + '.' + '$2');
      }
      return x1 + x2;
  }
  public toddmmyyyy(input: string) {
      var ptrn = /(\d{4})\-(\d{2})\-(\d{2})/;
      if(!input || !input.match(ptrn)) {
          return null;
      }
      return input.replace(ptrn, '$3/$2/$1');
  };

  public mes(d) {
    if (d == null) {
      return '??';
    }
    else {
      var m = parseInt(d.substring(5,7));
      return this.meses[m];
    }
  }
  private headers() {
      let headers = new Headers();
      headers.append('Accept', 'application/json');
      headers.append('Content-Type', 'application/json');
      headers.append('Authorization', 'Bearer '+this.perfil.token);
      let options = new RequestOptions({ headers: headers });
      return options;
  }

  formatDate(obj) {
    return obj.toString().replace(/\s/g, "T");
  }
}