import { Component, OnInit } from '@angular/core';
import { ModalController, MenuController, NavController, LoadingController } from '@ionic/angular';
import { EventService } from '../../../services/event.service';
import { AddcardPage } from 'src/app/pages/card/addcard/addcard.page';
import { ActivatedRoute } from '@angular/router';
import { NgForm } from '@angular/forms';
import { EnvService } from 'src/app/services/env.service';
import { AuthService } from 'src/app/services/auth.service';
import { IchambaService } from 'src/app/services/ichamba.service';
import { AlertService } from 'src/app/services/alert.service';

declare var OpenPay: any;

@Component({
  selector: 'app-extra',
  templateUrl: './extra.page.html',
  styleUrls: ['./extra.page.scss'],
  standalone: false
})
export class ExtraPage implements OnInit {

  private loading: HTMLIonLoadingElement | null = null;
  amount: number | null = null;
  amount_check = true;
  code_check = true;
  cards: any[] = [];
  card_id: any = null;
  supplier: any = null;
  cards_menu: any = null;
  contract_id: number | null = null;

  constructor(
    private modalController: ModalController,
    private menu: MenuController,
    private authService: AuthService,
    private alertService: AlertService,
    private ichambaService: IchambaService,
    private activatedRoute: ActivatedRoute,
    private navCtrl: NavController,
    private loadingCtrl: LoadingController,
    private events: EventService,
    private env: EnvService,
  ) {
    this.events.subscribe('refreshcards', (data) => {
      this.card_id = null;
      this.getcards();
    });
    this.supplier = this.activatedRoute.snapshot.paramMap.get('supplier');
    this.contract_id = Number(this.activatedRoute.snapshot.paramMap.get('contract_id'));
   }

  ngOnInit() {
    OpenPay.setId(this.env.MERCHANT_ID);
    OpenPay.setApiKey(this.env.PUBLIC_API_KEY);
    OpenPay.setSandboxMode(false);
    console.log(OpenPay.getSandboxMode());
    var deviceDataId = OpenPay.deviceData.setup("card_form");
    this.getcards();
  }

  newcard() {
    this.navCtrl.navigateForward('/addcard');
  }

  getcards() {
    this.ichambaService.getCard().subscribe(
      data => {
        this.cards = data;
      }, error => {
        this.alertService.presentToast("Por favor contacte a soporte técnico, Estatus:" + error['status']);
      });
  }

  check (ev: any) {
    this.amount = parseFloat(ev.target.value.replace(",", ""));
    console.log(this.amount);
    if (this.amount < 150) {
      this.amount_check = false;
    } else {
      this.amount_check = true;
    }
  }

  code_checker(ev: any) {
    this.code_check = OpenPay.card.validateCVC(ev.target.value);
    console.log(this.code_check);
  }

  selected_card(ev: any) {
    this.card_id = ev.target.value;
    console.log(this.card_id);
    if (this.card_id == "Agregar tarjeta") {
      console.log(this.card_id);
      this.newcard();
    }
  }

  addExtra(form: NgForm) {
    if (this.card_id != "Agregar tarjeta") {
      if (this.code_check) {
            let code = form.value.code;
            let device_id = (<HTMLInputElement>document.getElementById('deviceDataId')).value;
            console.log(device_id);
            this.loadingCtrl.create().then((overlay) => {
              this.loading = overlay;
              this.loading.present();
            });
            this.ichambaService.addExtra(this.contract_id!, this.amount!, this.card_id, code, device_id).subscribe(
              (data: any) => {
                if (this.loading) this.loading.dismiss();
                if (data['message'] == 'extra_added') {
                  this.alertService.presentToast("Fondo extra añadido con éxito");
                }
                this.events.publish('refreshpcontracts', 'data');
                this.navCtrl.navigateRoot('/contracts/contracted');
              }, (error: any) => {
                if (this.loading) this.loading.dismiss();
                this.alertService.presentToast("Por favor contacte a soporte técnico, Estatus:" + error['status']);
              });
            //console.log(onSuccess.data.id);
            //console.log(document.getElementById('deviceDataId').value);
      }
    } else {
      this.alertService.presentToast("Por favor seleccione una tarjeta");
    }
  }

}
