import { Component } from '@angular/core';
import { NavController, NavParams, LoadingController, AlertController } from 'ionic-angular';
import { GoogleAnalytics } from 'ionic-native';
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 * as global from '../../global';
import { Storage } from '@ionic/storage';

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

export class Sub {
  
  public element: any;
  public perfil: any;
  public modulo: any = {id: 0, fecha_inicio: new Date() };
  public desdeBBDD: boolean = false;
  public meses: any;
  public loading: any;
  public modulos: any[] = [];
  public primaryTab: boolean = true;
  public secondTab: boolean = false;
  public modoSinConexion: boolean = false;
  public alumnos: any[] = [];
  public synctxt: string = '';
  public intervalo: any = null;
  public activo: number = 0;
  public notifyRequest: boolean = true;
  public popupRequest: boolean = true;
  public overlayHidden: boolean = true;
  public man: any;
  public enCurso: any = { nombre: '' };


  constructor(public navCtrl: NavController, 
              private network: Network, 
              private alertCtrl: AlertController, 
              public http: Http, 
              private service: Lipigas, 
              public loadingController: LoadingController, 
              public params: NavParams,
              private storage: Storage
  ) {  
    this.element = params.get("element");
    this.perfil = JSON.parse(localStorage.getItem("LipigasPersonas"));
    this.meses = ['','ENE','FEB','MAR','ABR','MAY','JUN','JUL','AGO','SEP','OCT','NOV','DIC'];
    GoogleAnalytics.trackView("Detalle del curso");
    this.synctxt = 'Nunca';
    this.man = { motivo: '', rut: '' };
    this.storage.get("link_"+this.element.id).then((val) => {
      if (val != null) {
        this.synctxt = val;
      }
    });
    
    this.modulos = this.element.modulos;

    if (this.element.activoID != 0) {
      for (var i = 0; i < this.element.modulos.length; i++) {
        if (this.element.modulos[i].id == this.element.activoID && this.element.modulos[i].tipo == this.element.activoTipo) {
          this.enCurso = this.element.modulos[i];
        }
      }
    }

    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);

  }

  ngOnDestroy() {
    if (this.intervalo) {
      clearInterval(this.intervalo);
    }
  }

  public enrolateManual() {
    this.man = { motivo: '', rut: '' };
    this.notifyRequest = false;
    this.overlayHidden = false;
  }
  public closeNotify() {
    this.notifyRequest = true;
    this.overlayHidden = true;
  }
  public enrolarManualOK() {

    if (this.man.rut.trim() == '') {
      this.service.logError(null, "Rut no puede estar vacío");
    }
    else if (!this.rut(this.man.rut.trim())) {
      this.service.logError(null, "Rut inválido");
    }
    else if (this.man.motivo.trim() == '') {
      this.service.logError(null, "Motivo no puede estar vacío");
    }
    else {
      this.loading = this.loadingController.create({content:'enrolando...'});
      this.loading.present();

      this.storage.get("als_"+this.enCurso.id+"_"+this.enCurso.tipo).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 == this.man.rut) {
            x[z].estado = 1;
            x[z].fecha = fff;
            x[z].metodo = 'manual';
            x[z].motivo = this.man.motivo;
            x[z].latitud = '';
            x[z].longitud = '';
            x[z].sync = 0;
            x[z].mdl_id = this.enCurso.id;
            x[z].mdl_tipo = this.enCurso.tipo;
            f = 1;
          }
        }
        if (f == 0) {
          var o = {
            rut: this.man.rut,
            sync: 0,
            estado: 1,
            fecha: fff,
            motivo: this.man.motivo,
            offline: 1,
            metodo: 'manual',
            latitud: '',
            longitud: '',
            mdl_id: this.enCurso.id,
            mdl_tipo: this.enCurso.tipo
          };
          x.push(o);
          this.loading.dismiss();
          this.service.showMsg("RUT "+this.man.rut+" ingresado con éxito");
        }
        else {
          if (found.estado == 1) {
            this.loading.dismiss();
            this.service.showMsg("RUT "+this.man.rut+" ya está presente");
          }
          else {
            this.loading.dismiss();
            this.service.showMsg("RUT "+this.man.rut+" ingresado con éxito");
          }
        }
        this.storage.set("als_"+this.enCurso.id+"_"+this.enCurso.tipo, x);

        this.notifyRequest = true;
        this.overlayHidden = true;

      });
    }

  }

  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 changeModulo(newVal: string) {

  
    if (newVal == '' || newVal == '0') { 
      this.activo = 0;
      this.alumnos = [];
    }
    else { 
      var p = newVal.split('|');
      this.activo = parseInt(p[0]); 
      var tipo = p[1];
      this.modulo.fecha_inicio = p[2];


      this.loading = this.loadingController.create({content:'cargando...'});
      this.loading.present();

      this.storage.get("als_"+this.activo+"_"+tipo).then(x => {
        this.loading.dismiss();
        this.alumnos = x;
      });

      /*
      if (navigator.onLine == true) {

        this.http.get(global.api+'/cursos/enrolar/'+this.activo+'/'+tipo+'/alumnos', this.headers())
        .map(res => res.json())
        .subscribe(
          data => {
            this.loading.dismiss();
            this.alumnos = data.resultado;
          },
          err => {
            this.loading.dismiss();
            this.service.logError(null, "No se pudo obtener la información");
          }
        );

      }
      */

    }
  
  }

  public manual() {
    


    this.loading = this.loadingController.create({content:'sincronizando...'});
    this.loading.present();
    
    this.activo = 0;
    this.modulo.id = 0;

    this.service.sync('manual');

    var d = new Date();
    var ahora2 =
        ("00" + d.getDate()).slice(-2) + "/" + 
        ("00" + (d.getMonth() + 1)).slice(-2) + "/" + 
        d.getFullYear() + " " + 
        ("00" + d.getHours()).slice(-2) + ":" + 
        ("00" + d.getMinutes()).slice(-2) + ":" + 
        ("00" + d.getSeconds()).slice(-2);

    this.storage.set("link_"+this.element.id,ahora2).then(() => {
      this.storage.get("link_"+this.element.id).then((val) => {
        if (val != null) {
          this.synctxt = val;
        }
      });
    });

    this.loading.dismiss();
      

  }


  /* *********************** */
  /*    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");
  }

}