import { Component, ViewChildren, ViewChild } from '@angular/core';
import {CurrencyPipe} from '@angular/common';
import { NavController, ModalController, LoadingController, AlertController, Content, VirtualScroll } from 'ionic-angular';

import { DoctorService } from '../../services/doctor.service';
import { Pata } from '../../pata';
import { environment } from "../../environments/environment"
import * as moment from 'moment';
import { VerRecorridoPage } from '../ver-recorrido/ver-recorrido';
import { InAppBrowser } from '@ionic-native/in-app-browser';
import { ModalPagoOkPage } from '../../modals/modal-pago-ok/modal-pago-ok';
import { UserService } from '../../services/user.service';

@Component({
  selector: 'page-pagos',
  templateUrl: 'pagos.html'
})
export class PagosPage {
  
  shownGroup = null;
  cards: any = [];
  balance: number = 0;
  amount: number = null;
  loading: any = null; 
  token: string = '';
  user: any = {id: '0'};
  superload: any = null;

  constructor(
    public navCtrl: NavController,
    public modalCtrl: ModalController,
    public loadingCtrl: LoadingController,
    private alertCtrl: AlertController,
    public iab: InAppBrowser,
    public service: Pata,
    public userService: UserService,
    private doctorService: DoctorService) {
      this.doctorService.getToken().subscribe((data:any) => {
        this.token = data;
      });
      this.userService.getProfile().subscribe((result:any)=>{
        this.user = result;
      });
      
      
  }
  ionViewDidEnter(){
    this.getTarjetas(1);
  }
  getTarjetas(starting?:number) {
    this.superload = this.loadingCtrl.create();
    this.superload.present();
    this.doctorService.getCards().subscribe((data:any) => {
      this.cards = data.data;
      if (starting) {
        this.getBalance(1); 
      }
      else {
        this.superload.dismiss();
      }
    }, (err) => {
      if (starting) {
        this.getBalance(1); 
      }
      else {
        this.superload.dismiss();
      }
    });

  }
  getBalance(starting?:number) {
    if (!starting) {
      this.superload = this.loadingCtrl.create();
      this.superload.present();
    }
    this.doctorService.getBalance().subscribe((data:any) => {
      this.balance = data.balance;
      this.superload.dismiss();
    }, (err) => {
      this.superload.dismiss();
    });
  }  
  deleteTarjeta(index:number) {
    let id = this.cards[index].id;
    let alert = this.alertCtrl.create({
      title: '',
      message: '¿Desea eliminar esta tarjeta?',
      buttons: [
        { text: 'Cancelar', role: 'cancel', handler: () => { } },
        { text: 'Si', handler: () => { this.deleteTarjetaOk(id); } }
      ]
    });
    alert.present();
  } 
  deleteTarjetaOk(id){
    this.superload = this.loadingCtrl.create();
    this.superload.present();

    this.doctorService.deleteTarjeta(id).subscribe((data:any)=>{
      this.superload.dismiss();
      if (data.res == "OK"){
        this.service.showOk();
        this.getTarjetas();        
      } else{
        this.service.showMsg(data.msg);
      }
    },(err)=>{
      this.service.showMsg("No fue posible eliminar la tarjeta");
    });
  } 
  dateformat(fecha){
    var fecha_mm = moment(fecha);
    return moment(fecha_mm.format(),moment.ISO_8601).format();
  }

  addCard() {
    const browser = this.iab.create(environment.apiUrl+'customers/enroll?token='+this.token, '_blank', {
      location: 'no',
      zoom: 'no',
      hardwareback: 'no',
      hideurlbar: 'yes',
      closebuttoncaption: 'Cancelar'
    });

    browser.on('loadstop').subscribe(event => {
      if (event.url.indexOf("appFinish2") > 0) {

        if (event.url.indexOf("success") > 0) {
          browser.close();        
          this.getTarjetas();
          let alert = this.alertCtrl.create({
            title: 'Listo',
            subTitle: "Se ha enrolado la tarjeta correctamente",
            buttons: ['Aceptar']
          });
          alert.present();
          
        } else if (event.url.indexOf("error") > 0) {
          browser.close();
          let alert = this.alertCtrl.create({
            title: 'Error',
            subTitle: "No fue posible enrolar tu tarjeta, intenta nuevamente o comunicate con tu banco",
            buttons: ['Aceptar']
          });
          alert.present();
        }
       }      
    });

  }

  loadBalance() {
    let amount = this.amount;
    if (amount < 1) {
      let alert = this.alertCtrl.create({
        title: 'Error',
        subTitle: "Monto a abonar debe ser superior a cero",
        buttons: ['Aceptar']
      });
      alert.present();
    }
    else {
      const browser = this.iab.create(environment.apiUrl+'customers/addfunds?amount='+amount+'&token='+this.token, '_blank', {
        location: 'no',
        zoom: 'no',
        hardwareback: 'no',
        hideurlbar: 'yes',
        closebuttoncaption: 'Cancelar'
      });


      this.amount = 0;

      browser.on('loadstop').subscribe(event => {
        if (event.url.indexOf("wsFinish") > 0) {
  
          if (event.url.indexOf("success") > 0) {
            browser.close();          
            this.getBalance();
            let ex = event.url.split('id=');
            let x = this.modalCtrl.create(ModalPagoOkPage, { id: ex[1] });
            x.present();
            /*
            let alert = this.alertCtrl.create({
              title: 'Listo',
              subTitle: "Se han abonado los fondos a tu cuenta GreenApp",
              buttons: ['Aceptar']
            });
            alert.present();
            */
            
          } else if (event.url.indexOf("error") > 0) {
            browser.close();
            let alert = this.alertCtrl.create({
              title: 'Error',
              subTitle: "No fue posible realizar la carga, intenta nuevamente o comunicate con tu banco",
              buttons: ['Aceptar']
            });
            alert.present();
          }
         }      
      });

    }
  }
}


