import { Component, OnInit } from '@angular/core';
import {AlertController, NavController} from "@ionic/angular";
import {Router} from "@angular/router";
import { BarcodeScanner } from '@capacitor-community/barcode-scanner';
import {WrenchService} from "../../services/wrench.service";
import {SessionDataProviderService} from "../../store/session-data-provider.service";
import {BlogDataService} from "../../store/blog-data.service";
@Component({
  selector: 'app-startscan',
  templateUrl: './startscan.page.html',
  styleUrls: ['./startscan.page.scss'],
})
export class StartscanPage implements OnInit {

  content_visibility = '';
  tabs = 'about';

  constructor(
      private navctr: NavController,
      private router: Router,
      private wrenchService: WrenchService,
      public sessionDataProviderService:SessionDataProviderService,
      public blogDataService:BlogDataService,
      private alertController: AlertController
  ) { }
  loginResult: any;
  blogResult:any;
  ngOnInit() {
    this.startScan();
  }

  onBack() {
    this.stopScan();
    this.navctr.back();
  }

  loginQrData: {
    username: string,
    sessionid: string,
    action: number,
    login_mode: number
  };
  startQRLogin(qrString) {
    if (qrString == null || qrString == '' ) {
      return;
    }
  //  alert(qrString);
    this.loginQrData = { username: qrString,
                         sessionid: 'DUMMY-APP-SESSION-STARTER',
                         action: 11022,
                         login_mode: 1105 };
  //  alert(1000);
    this.wrenchService.qrLoginUser(this.loginQrData).subscribe(
        loginResult => {
         // alert("Here 00009");
          this.loginResult = loginResult;
          console.log("INTERNAL RETURN->" + this.loginResult.internal_return);
          if (loginResult != null
              && loginResult.internal_return == 100
              && this.sessionDataProviderService.ConstructGlobalSessionData(this.loginResult) == true) {
           // alert("Here 00009a");
           // this.getBlogData();
            this.router.navigate(['tabs/tab1']);
          }
          else{
            this.showAlert("Error","Unable to use the code to login");
            this. stopScan();
          }
        }
    );
  }

  async checkPermission() {
    try {
      // check or request permission
      const status = await BarcodeScanner.checkPermission({ force: true });
      if (status.granted) {
        // the user granted permission
        return true;
      }
      return false;
    } catch(e) {
      console.log(e);
    }
  }
  scannedResult:any;
  async startScan() {
    try {
      const permission = await this.checkPermission();
      if(!permission) {
        this. stopScan();
        return;
      }
      await BarcodeScanner.hideBackground();
      document.querySelector('body').classList.add('scanner-active');
      this.content_visibility = 'hidden';
      const result = await BarcodeScanner.startScan();
      console.log(result);
      BarcodeScanner.showBackground();
      document.querySelector('body').classList.remove('scanner-active');
      this.content_visibility = '';
      if(result?.hasContent) {
        this.scannedResult = result.content;
        console.log(this.scannedResult);
        this.startQRLogin( this.scannedResult );
      }
    } catch(e) {
      console.log(e);
      this.stopScan();
    }
  }

  stopScan() {
    BarcodeScanner.showBackground();
    BarcodeScanner.stopScan();
    document.querySelector('body').classList.remove('scanner-active');
    this.content_visibility = '';
    this.navctr.back();
  }
  async showAlert(mtitle: string, amessage: string) {
    const alert = await this.alertController.create({
      header: 'WrenchBoard',
      subHeader: mtitle,
      message: amessage,
      buttons: ['OK'],
    });

    await alert.present();
  }

}
