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 { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import { CursosListar } from '../../pages/cursos/listar';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import * as global from '../../global';

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

export class CursosDetalle {
  public login: any;
  public loading: any;
  public relatores: any[] = [];
  public curso: any;
  public perfil: any;
  public id: any = null;
  public tipo: any = null;
  public meses: any;

  constructor(public navCtrl: NavController, private alertCtrl: AlertController, public params: NavParams, public http: Http, private service: Lipigas, public loadingController: LoadingController, private sanitizer: DomSanitizer) { 
    this.curso = {
      aceptado: null,
      aprobado: null,
      descripcion: "",
      enroladores: [],
      estado: 0,
      fecha_inicio: "",
      fecha_termino: "",
      icono_curso: "",
      id: 0,
      lugar: "",
      modulos: [],
      nombre: "",
      relatores: [],
      tipo: 0
    }; 

    this.meses = ['','Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'];

    this.perfil = JSON.parse(localStorage.getItem("LipigasPersonas"));
    this.id = params.get("id");
    this.tipo = params.get("tipo");
    this.http.get(global.api+'/cursos/'+this.id+'/listado', this.headers())
    .map(res => res.json())
    .subscribe(
      data => this.processVerCurso(data,'ok'),
      err => this.processVerCurso(err,'err')
    );
    this.loading = this.loadingController.create({content:'obteniendo información...'});
    this.loading.present();

    GoogleAnalytics.trackView("Ver curso");
    GoogleAnalytics.trackEvent("Curso", "Detalle", "ID", this.id);
  }


  public processVerCurso(obj: any, res: string) {
    this.loading.dismiss();
    if (res == 'ok') {
      this.curso = obj.resultado;
      console.log(this.curso);
      this.relatores = obj.resultado.relatores;
    }
    else if (res == 'err') { 
      this.service.logError(obj, 'No fue posible obtener la información. Por favor intenta más tarde.'); 
    }
  }


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

  public goBack() {
   this.navCtrl.pop();
   //setRoot(CursosListar, {tipo: this.tipo}, { animate: true, direction: 'back' });
  }
  public mes(d) {
    if (d == null) {
      return '??';
    }
    else {
      var m = parseInt(d.substring(5,7));
      return this.meses[m];
    }
  }
  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');
  };

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