import { Router } from '@angular/router';
import { Component, OnInit, ViewChild } from '@angular/core';
import { WrenchService } from 'src/app/services/wrench.service';
import { SessionDataProviderService } from 'src/app/store/session-data-provider.service';
import { BlogDataService } from 'src/app/store/blog-data.service';
import {NavController} from "@ionic/angular";
import { AlertController } from '@ionic/angular';
//import { BarcodeScanner } from '@capacitor-community/barcode-scanner';

@Component({
  selector: 'app-familylogin',
  templateUrl: './familylogin.page.html',
  styleUrls: ['./familylogin.page.scss'],
})
export class FamilyloginPage implements OnInit {
//Y7P0WW9B05
  // 1234

  @ViewChild('username') username;
  @ViewChild('pin') pin;
  loginResult: any;
  blogResult:any;
  content_visibility = '';

  constructor(
      private router: Router,
      private wrenchService: WrenchService,
      public sessionDataProviderService:SessionDataProviderService,
      public blogDataService:BlogDataService,
      private navctr: NavController,
      private alertController: AlertController
  ) {

  }

  ngOnInit() {
  }

  loginData: {
    username: string, pin: string, sessionid: string, action: '11025',login_mode: '1105'
  };
  startLogin() {
    // this.username='Y7P0WW9B05';
    // this.pin='1234';
    if (this.username == null || this.username == '' || this.pin == null || this.pin == '') {
      this.showAlert('Invalid Login', 'Enter username(email) and pin to login');
      return;
    }
    this.loginData = { username: this.username, pin: this.pin, sessionid: 'DUMMY-APP-SESSION-STARTER', action: '11025',login_mode: '1105' }
    this.wrenchService.loginUser(this.loginData).subscribe(
        loginResult => {
          this.loginResult = loginResult;
          console.log("INTERNAL RETURN->" + this.loginResult.internal_return);
          if (loginResult != null && loginResult.internal_return == 100 && this.sessionDataProviderService.ConstructGlobalSessionData(this.loginResult) == true) {
            this.getBlogData();
            this.router.navigate(['tabs/tab1']);
          }
          else{
            this.showAlert("Error","Invalid Username/pin");
          }
        }
    );
  }

  onBack() {
    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();
  }

  getBlogData(){
    this.wrenchService.getBlogData([]).subscribe(
        blogResult => {
          this.blogResult = blogResult;
          console.log("BLOG RETURN->", this.blogResult);
          this.blogDataService.setBlogData(this.blogResult.blogdata);
        }
    );
  }

  userLogin(){
    this.router.navigate(['login']);
  }

moveToStartScan(){
  this.router.navigate(['startscan']);
}

}
