import { Component, OnInit } from '@angular/core';
import { SMSService } from './service/smsservice';
import { ModalController, NavParams } from '@ionic/angular';
import { CommonService } from 'src/app/hmg-common/services/common/common.service';
import { TranslatorService } from 'src/app/hmg-common/services/translator/translator.service';
import { Response } from 'src/app/hmg-common/services/models/response';
import { SmsReaderService } from 'src/app/hmg-common/services/sms/sms-reader.service';
// import { UserDetailsModel } from 'src/app/h2o/service/models/user-details.model';
// import { SendValidationResponse } from 'src/app/h2o/service/models/send-activation.response';
import { SharedDataService } from 'src/app/hmg-common/services/shared-data-service/shared-data.service';
import { CountryCode } from 'src/app/hmg-common/ui/mobile-number/international-mobile/models/country-code.model';
import { SmsPopComponent } from './sms-pop/sms-pop.component';
import { AlertController } from '@ionic/angular';

@Component({
  selector: 'sms-pop-page',
  templateUrl: './sms.page.html',
  styleUrls: ['./sms.page.scss'],
})
export class SmsPage implements OnInit {
  constructor(public cs: CommonService,
              public ts: TranslatorService,
              public alertController: AlertController,
              public smsService: SmsReaderService,
              public sharedData: SharedDataService,
              private modalCtrl: ModalController,
              private navParams: NavParams,
              public smsservice: SMSService) {
      this.initTimer();
      this.startTimer();

      // this.smsservice.sendActivationCode(this.id, this.mobile,
      //   this.country_code, () => { },
      //       this.ts.trPK('general', 'ok')).subscribe((result: SendValidationResponse) => {
      //           if (this.cs.validResponse(result)) {
      //               if (result.isSMSSent) {
      //               } else {
      //                   this.stopSMSMonitoring();
      //               }
      //           } else {
      //               this.stopSMSMonitoring();
      //           }
      //       });
           }
  public static SHARED_DATA = 'h2o-login-details';
  public timeInSeconds: number ;
  public time: number;
  public runTimer: boolean;
  public hasStarted: boolean;
  public countryCode: CountryCode;
  public hasFinished: boolean;
  public remainingTime: number;
  public displayTime = '';
  // public userData: UserDetailsModel;
  public mobile: string;
  // tslint:disable-next-line: variable-name
  public country_code: string;
  public id: string;
  public MobileNumber: string;
  public token: string;
  public resend = false;
  public smc_code: any;

  ngOnInit() {
  }


  closeModal() {
    this.modalCtrl.dismiss();
  }

  cancelModal() {
    this.modalCtrl.dismiss({ cancelled: true });
  }

  initTimer() {
    if (!this.timeInSeconds) {
      this.timeInSeconds = 60;
    }
    this.time = this.timeInSeconds;
    this.runTimer = false;
    this.hasStarted = false;
    this.hasFinished = false;
    this.remainingTime = this.timeInSeconds;
    this.displayTime = this.getSecondsAsDigitalClock(this.remainingTime);
  }

  startTimer() {
    this.runTimer = true;
    this.hasStarted = true;
    this.resend = false;
    this.timerTick();
  }

  pauseTimer() {
    this.runTimer = false;
  }

  resumeTimer() {
    this.startTimer();
  }

  timerTick() {
    setTimeout(() => {
      if (!this.runTimer) { return; }
      this.remainingTime--;
      this.displayTime = this.getSecondsAsDigitalClock(this.remainingTime);
      if (this.remainingTime > 0) {
        this.timerTick();
      } else {
        this.hasFinished = true;
        this.resend = true;
      }
    }, 1000);
  }

  getSecondsAsDigitalClock(inputSeconds: number) {
    let sec_num = parseInt(inputSeconds.toString(), 10); // don't forget the second param
    let hours = Math.floor(sec_num / 3600);
    let minutes = Math.floor((sec_num - (hours * 3600)) / 60);
    let seconds = sec_num - (hours * 3600) - (minutes * 60);
    let hoursString = '';
    let minutesString = '';
    let secondsString = '';
    hoursString = (hours < 10) ? '0' + hours : hours.toString();
    minutesString = (minutes < 10) ? '0' + minutes : minutes.toString();
    secondsString = (seconds < 10) ? '0' + seconds : seconds.toString();
    return minutesString + ':' + secondsString;
  }

  validate() {
    // this.checkSMSActivationCode(this.smc_code);
    SMSService.code = this.smc_code;
    this.stopSMSMonitoring();
    this.modalCtrl.dismiss();
    SMSService.modal_success = true;
  }

  async presentAlert() {
    const alert = await this.alertController.create({
      header: 'Alert',
      message: 'Incorrect OTP, Please enter correct OTP.',
      buttons: ['OK']
    });

    await alert.present();
  }

  private checkSMSActivationCode(smsCode: string) {
    this.smsservice.validateActivationCode(this.token, smsCode,
        () => {}, this.ts.trPK('settings', 'incorrect_otp')).subscribe((result: Response) => {
            if (this.cs.validResponse(result)) {
            }
        });
  }

  public stopSMSMonitoring() {
      this.smsService.stopSMSMonitoring();
  }

  public ResendOTP() {
    this.id = SMSService.national_id;
    this.mobile = SMSService.mobile_number;
    this.country_code = SMSService.country_code;
    console.log(this.id);
    console.log(this.mobile);
    console.log(this.country_code);

    const zip = this.country_code;
    // if (this.country_code.indexOf('+') !== -1) {
    //   zip = this.country_code.substring(this.country_code.indexOf('+') + 1);
    // }
    // this.smsservice.sendActivationCode(SMSService.sendBloodDonationSMS,this.id, this.mobile,
    //   zip, () => { },
      // this.ts.trPK('general', 'ok')).subscribe((result: SendValidationResponse) => {
      //     if (this.cs.validResponse(result)) {
      //         if (result.isSMSSent) {
      //           this.initTimer();
      //           this.startTimer();
      //         } else {
      //           this.stopSMSMonitoring();
      //         }
      //     } else {
      //         this.stopSMSMonitoring();
      //     }
      // });
  }


}
