import { Component, OnInit } from '@angular/core';
import { ModalController, MenuController, NavController, LoadingController } from '@ionic/angular';
import { EventService } from '../../../services/event.service';
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';
import { TranslateService } from '@ngx-translate/core';

declare var OpenPay: any;

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

  private loading: HTMLIonLoadingElement | null = null;
  card_check = true;
  date_check = true;
  cvv_check = true;
  holder_check: boolean | null = null;
  line1_check: boolean | null = null;
  line2_check: boolean | null = null;
  line3_check: boolean | null = null;
  postal_code_check: boolean | null = null;
  city_check: boolean | null = null;
  state_check: boolean | null = null;
  month_number: any = null;
  year_number: any = null;

  constructor(
    private modalController: ModalController,
    private menu: MenuController,
    private authService: AuthService,
    private alertService: AlertService,
    private ichambaService: IchambaService,
    private translateService: TranslateService,
    private navCtrl: NavController,
    private loadingCtrl: LoadingController,
    private events: EventService,
    private env: EnvService,
  ) { }

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

  card_checker(ev: any) {
    if (ev.target.value.length > 16) {
      console.log(ev.target.value.length);
      ev.target.value = ev.target.value.slice(0, 16);
    }
    this.card_check = OpenPay.card.validateCardNumber(ev.target.value);
    console.log(this.card_check);
  }

  month_checker(ev: any) {
    if (ev.target.value.length > 2) {
      console.log(ev.target.value.length);
      ev.target.value = ev.target.value.slice(0, 2);
    }
    this.month_number = ev.target.value;
    this.date_check = OpenPay.card.validateExpiry(this.month_number, this.year_number);
    console.log(this.month_number);
  }

  year_checker(ev: any) {
    if (ev.target.value.length > 2) {
      console.log(ev.target.value.length);
      ev.target.value = ev.target.value.slice(0, 2);
    }
    this.year_number = ev.target.value;
    this.date_check = OpenPay.card.validateExpiry(this.month_number, this.year_number);
    console.log(this.card_check);
  }

  cvv_checker(ev: any) {
    if (ev.target.value.length > 4){
      console.log(ev.target.value.length);
      ev.target.value = ev.target.value.slice(0, 4);
    }
    this.cvv_check = OpenPay.card.validateCVC(ev.target.value);
    console.log(this.cvv_check);
  }

  holder_checker(ev: any) {
    this.holder_check = (ev.target.value == '' ? false : true);
    console.log(this.holder_check);
  }

  line1_checker(ev: any) {
    this.line1_check = (ev.target.value == '' ? false : true);
    console.log(this.line1_check);
  }

  line2_checker(ev: any) {
    this.line2_check = (ev.target.value == '' ? false : true);
    console.log(this.line2_check);
  }

  line3_checker(ev: any) {
    this.line3_check = (ev.target.value == '' ? false : true);
    console.log(this.line3_check);
  }

  postal_code_checker(ev: any) {
    this.postal_code_check = (ev.target.value == '' ? false : true);
    console.log(this.postal_code_check);
  }

  city_checker(ev: any) {
    this.city_check = (ev.target.value == '' ? false : true);
    console.log(this.city_check);
  }

  state_checker(ev: any) {
    this.state_check = (ev.target.value == '' ? false : true);
    console.log(this.state_check);
  }

  addcard(form: NgForm) {
    if (this.holder_check && this.card_check && this.date_check && this.cvv_check /*&& this.line1_check && this.line2_check && this.line3_check && this.postal_code_check && this.city_check && this.state_check*/) {
        this.loadingCtrl.create().then((overlay) => {
          this.loading = overlay;
          this.loading.present();
        });
        OpenPay.token.create({
          "card_number": form.value.card_number,
          "holder_name": form.value.holder_name,
          "expiration_year": form.value.expiration_year,
          "expiration_month": form.value.expiration_month,
          "cvv2": form.value.cvv2,
          /*"address":{
             "city": form.value.city,
             "line3": form.value.line3,
             "postal_code": form.value.postal_code,
             "line1": form.value.line1,
             "line2": form.value.line2,
             "state": form.value.state,
             "country_code":"MX"
          }*/
        },
        (onSuccess: any) => {
          let token = onSuccess.data.id;
          let device_id = (<HTMLInputElement>document.getElementById('deviceDataId')).value;
          this.ichambaService.addCard(token, device_id).subscribe(
            (data: any) => {
              if (data['type'] == "error") {
                if (this.loading) this.loading.dismiss();
                this.alertService.presentToast(data['message']);
              } else {
                this.events.publish('refreshcards', 'data');
                if (this.loading) this.loading.dismiss();
                this.dismissAddcard();
                this.alertService.presentToast(this.translateService.instant('alerts.added_card'));
              }
            }, (error: any) => {
              if (this.loading) this.loading.dismiss();
              this.alertService.presentToast(this.translateService.instant('alerts.error') + error['status']);
            });
          //console.log(onSuccess.data.id);
          //console.log(document.getElementById('deviceDataId').value);
        }, (onError: any) => {
            if (this.loading) this.loading.dismiss();
            this.alertService.presentToast(this.translateService.instant('alerts.geo_error') + onError['status']);
        });
    }
  }

  dismissAddcard() {
    this.navCtrl.back();
  }

}
