import { Component } from '@angular/core';
import { NavController, NavParams, LoadingController, AlertController } from 'ionic-angular';
import { GoogleAnalytics } from 'ionic-native';
import { Lipigas } from '../../lipigas';
import { CursosDetalle } from '../../pages/cursos/detalle';
import { Http, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import * as global from '../../global';

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

export class CursosListar {
  public tipo: any = null;
  public showInfobox: number[] = [];
  public htmlInfobox: string[] = [];
  public relaInfobox:Array<Object> = [];
  public login: any;
  public loading: any;
  public primaryTab: boolean = true;
  public secondTab: boolean = false;
  public pendientes: any[] = [];
  public historial: any[] = [];
  public notifyRequest: boolean = true;
  public popupRequest: boolean = true;
  public overlayHidden: boolean = true;
  public perfil: any;
  public IDTrxActiva: number;
  public IDColActiva: number;
  public NNActiva: string;
  public rechazo: any;
  public numPend: number = 0;
  public numHist: number = 0;
  public maxpagPend: number = 0;
  public maxpagHist: number = 0;
  public hasMoreDataPend: boolean = true;
  public hasMoreDataHist: boolean = true;
  public meses: any;
  public showDetalleMotivo: boolean = false;

  constructor(public navCtrl: NavController, private alertCtrl: AlertController, public http: Http, private service: Lipigas, public loadingController: LoadingController, public params: NavParams) {  
    this.perfil = JSON.parse(localStorage.getItem("LipigasPersonas"));
    this.tipo = params.get("tipo");
    this.loadTab1(1,null);
    this.rechazo = { motivo: '', motivo2: '' };
    this.meses = ['','ENE','FEB','MAR','ABR','MAY','JUN','JUL','AGO','SEP','OCT','NOV','DIC'];
    GoogleAnalytics.trackView("Cursos");
  }


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

  togglePendientes() {
    this.pendientes = [];
    this.loadTab1(1,null);
    this.secondTab = false;
    this.primaryTab = true;
  }

  toggleHistorial() {
    this.historial = [];
    this.loadTab2(1, null);
    this.secondTab = true;
    this.primaryTab = false;
  }

  /* *************************** */
  /*        Tab 1                */
  /* *************************** */ 

  public loadTab1(pag: number, infinite: any) {
    this.numPend = pag;

    this.http.post(global.api+'/cursos/listado', {
      pag: this.numPend,
      tipo: this.tipo,
      estado: 1
    }, this.headers())
    .map(res => res.json())
    .subscribe(
      data => this.processCursosPrePendiente(data,'ok',infinite),
      err => this.processCursosPrePendiente(err,'err',infinite)
    );

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

  public processCursosPrePendiente(obj: any, res: string, infinite: any) {
    if (infinite == null) { this.loading.dismiss(); }
    if (res == 'ok') {
      for (var i = 0;i < obj.resultado.length;i++) {
        if (obj.resultado[i].aceptado == 0) {
          obj.resultado[i].aceptado = -1;
        }
        if (obj.resultado[i].aceptado == null) {
          obj.resultado[i].aceptado = 0;
        }
      }
      this.pendientes = this.pendientes.concat(obj.resultado);
      this.maxpagPend = obj.total_paginas;

      if (this.numPend >= this.maxpagPend) {
        this.hasMoreDataPend = false;
      }
      else {
        this.hasMoreDataPend = true;
      }

    }
    else if (res == 'err') { 
      this.service.logError(obj, 'No fue posible obtener los cursos pendientes. Por favor intenta más tarde.'); 
    }

    if (infinite != null) {
      infinite.complete();
    }
  }

  public infobox(id: number, i: number) {
    this.navCtrl.push(CursosDetalle,{
      id: id,
      tipo: this.tipo
    });
  }

  doInfinitePend(infiniteScroll) {
    this.numPend = this.numPend+1;
    this.loadTab1(this.numPend, infiniteScroll);
  }

  /* ***************************** */ 
  /*          MODALES              */
  /* ***************************** */

  public closeConfirm() {
    this.popupRequest = true;
    this.overlayHidden = true;
  }
  public aceptar(id: number, i: number) {
    this.loading = this.loadingController.create({content:'aceptando...'});
    this.loading.present();

    this.http.post(global.api+'/cursos/'+id+'/confirmar', {
      respuesta: 1,
      motivo_rechazo: ""
    }, this.headers())
    .map(res => res.json())
    .subscribe(
      data => this.processCloseOperation(i,'ok', 1),
      err => this.processCloseOperation(i,'err', 0)
    );

  }

  public rechazar(id: number, i: number) {

    this.rechazo.motivo = '';
    this.rechazo.motivo2 = '';
    this.showDetalleMotivo = false;

    this.NNActiva = this.pendientes[i].nombre;
    this.IDTrxActiva = id;
    this.IDColActiva = i;
    this.popupRequest = true;
    this.notifyRequest = false;
    //this.popupRequest = false;
    this.overlayHidden = false;

  }

  public changeRechazo(newVal: string) {
    if (newVal == 'Otros') {
      this.rechazo.motivo = '';
      this.showDetalleMotivo = true;
    }
    else {
      this.rechazo.motivo = newVal;
      this.showDetalleMotivo = false;
    }
  }
  public closeNotify() {
    this.notifyRequest = true;
    this.overlayHidden = true;
  }
  public notificar() {

    if (this.rechazo.motivo == '') {
      this.service.logError(null, 'Debe ingresar un motivo'); 
    }
    else {
      this.notifyRequest = true;
      this.overlayHidden = true;
      this.loading = this.loadingController.create({content:''});
      this.loading.present();

      this.http.post(global.api+'/cursos/'+this.IDTrxActiva+'/confirmar', {
        respuesta: 0,
        motivo_rechazo: this.rechazo.motivo
      }, this.headers())
      .map(res => res.json())
      .subscribe(
        data => this.processCloseOperation(this.IDColActiva,'ok', -1),
        err => this.processCloseOperation(this.IDColActiva,'err', 0)
      );
    }


  }


  public processCloseOperation(i: number, res: string, estado: number) {
    this.loading.dismiss();
    if (res == 'ok') {
      this.pendientes[i].aceptado = estado;
    }
    else {
      this.service.logError(null, 'No fue posible la operación. Por favor intenta más tarde.'); 
    } 
  }

  public motivoRechazo() {
    this.popupRequest = true;
    this.notifyRequest = false;
  }

  public postSolicitar(fecha: string, horario: string) {
    var dt = new Date(this.formatDate(fecha));   
    var dn = new Date();
    if (dt <= dn) { 
      let conf = this.alertCtrl.create({
      title: 'Error',
        message: 'Por favor seleccione una fecha superior a la fecha actual',
        buttons: [
          {
            text: 'OK',
            role: 'cancel',
            handler: () => {
              
            }
          }
        ]
      });
      conf.present();
    }
    else {
      this.loading = this.loadingController.create({content:'solicitando...'});
      this.loading.present();

    }

  }  

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

  }

  /* ************************* */
  /*        TAB 2              */
  /* ************************* */

  public loadTab2(pag: number, infinite: any) {
    this.numHist = pag;

    this.http.post(global.api+'/cursos/listado', {
      pag: this.numHist,
      tipo: this.tipo,
      estado: 2
    }, this.headers())
    .map(res => res.json())
    .subscribe(
      data => this.processCursosPreHistorial(data,'ok', infinite),
      err => this.processCursosPreHistorial(err,'err', infinite)
    );

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

  public processCursosPreHistorial(obj: any, res: string, infinite: any) {
    if (infinite == null) { this.loading.dismiss(); }
    if (res == 'ok') {
      this.historial = this.historial.concat(obj.resultado);
      this.maxpagHist = obj.total_paginas;

      if (this.numHist >= this.maxpagHist) {
        this.hasMoreDataHist = false;
      }
      else {
        this.hasMoreDataHist = true;
      }

    }
    else if (res == 'err') { 
      this.service.logError(obj, 'No fue posible obtener el historial de los cursos. Por favor intenta más tarde.'); 
    }


    if (infinite != null) {
      infinite.complete();
    }

  }

  doInfiniteHist(infiniteScroll) {
    this.numHist = this.numHist+1;
    this.loadTab2(this.numHist, infiniteScroll);
  }

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