import { Component, OnInit, NgZone } from '@angular/core';
import { CommonService } from 'src/app/hmg-common/services/common/common.service';
import { attendanceSwipeScannerRequest } from 'src/app/home/models/attendanceSwipe.Request';
import { Device } from '@ionic-native/device/ngx';
import { AuthenticatedUser } from '../../hmg-common/services/authentication/models/authenticated-user';
import { AttendanceService } from 'src/app/home/services/attendance.services';
import { Response } from 'src/app/hmg-common/services/models/response';
import { ModalController } from '@ionic/angular';
import { TranslatorService } from 'src/app/hmg-common/services/translator/translator.service';
import { Platform } from "@ionic/angular";
import { WifiWizard2 } from "@ionic-native/wifi-wizard-2/ngx";
import { OpenNativeSettings } from '@ionic-native/open-native-settings/ngx';
import { AttendScanService } from "../../hmg-common/services/attend-services/attend-scan.service";

@Component({
  selector: 'app-wifi-modal',
  templateUrl: './wifi-modal.component.html',
  styleUrls: ['./wifi-modal.component.scss'],
})
export class WifiModalComponent implements OnInit {
  public userData: any = {};
  public gifStatus = false;
  private ssid =  CommonService.MOHEMM_WIFI_SSID;
  private password = CommonService.MOHEMM_WIFI_PASSWORD;
  private algo = 'WPA';
  public enableLocationWIFI: boolean;
  public lat: number;
  public longt: number;
  public failedObjectWIFI = {
    modeOfAttendance: 0,
    messageStatus: 0,
    transactionID: 0,
    userID: '',
    pointID: 0,
    branchDescription: 0 
  }

  constructor(
    public common: CommonService,
    private device: Device,
    private attendance_service: AttendanceService,
    public modalController: ModalController,
    public ts: TranslatorService,
    public ngZone: NgZone,
    private wifiWizard2: WifiWizard2,
    private openNativeSettings: OpenNativeSettings,
    private platform: Platform,
    public attendScanService: AttendScanService
  ) { }

  ngOnInit() {
    this.userData = this.common.sharedService.getSharedData(AuthenticatedUser.SHARED_DATA, false);
    setTimeout(() => {
      this.startWifiConnection();
    }, 1000);
  }

  async startWifiConnection() {
    const isAndroid = this.platform.is("android");
    const isIOS = this.platform.is("ios");

    if (isAndroid) {
      let isWifiAvailable = await this.isWifiAvailable(this.ssid);
      console.debug("isWifiAvailable: " + isWifiAvailable);
      if(isWifiAvailable){
        console.debug("Wifi Credientials:    " + this.ssid + " | " + this.password);
        this.wifiWizard2.connect(this.ssid, true, this.password, this.algo).then(async (value) =>{        
          let ssid_ = await this.wifiWizard2.getConnectedSSID();
          if(ssid_ == this.ssid){
            console.debug("Wifi Connected: Verified Access | " + value + " | " + ssid_);
            setTimeout(() => {
              this.swipeAttendanceWifi(ssid_);
            },2000);
          }else{
            this.showErrorInvalidWorkspace();
          }
        })
        .catch((err) => { 
          console.debug(err);
          this.showErrorForgetWifiConfiguration();
        });
      }else{
        console.debug("Wifi is not available considered your device is not in range");
        this.showErrorInvalidWorkspace();
      }
    } else if (isIOS) {
      this.wifiWizard2.iOSConnectNetwork(this.ssid,this.password).then(async (value) => {
        let ssid_ = await this.wifiWizard2.getConnectedSSID();
        if(ssid_ == this.ssid){
          console.debug("Wifi Connected: Verified Access | " + value + " | " + ssid_);
          setTimeout(() => {
            this.swipeAttendanceWifi(ssid_);
          },6000);
        }else{
          this.showErrorInvalidWorkspace();
        }
      })
      .catch((err) => { 
        console.debug(err);
        this.showErrorInvalidWorkspace();
      });
      if(this.wifiWizard2.isWifiEnabled){
      } else{
        this.showWifiNotEnabled();
      }
    }
  }​

  showWifiNotEnabled(){
    this.common.showErrorMessageDialog(()=>{
      this.openNativeSettings.open('wifi').then(()=>{});
    },
    this.ts.trPK("general", "ok"),
    this.ts.trPK("general","wifi-not-enable-text"));
  }

  showErrorInvalidWorkspace() {
    this.closeModal();
    this.common.showErrorMessageDialog(()=>{
    },
    this.ts.trPK("general", "ok"),
    this.ts.trPK("general","wifi-connection-failed-text"));
    this.disconnectWifi();
  }

  showErrorForgetWifiConfiguration() {
    this.closeModal();
    this.common.confirmAlertDialog(() => {
      this.openNativeSettings.open('wifi').then(()=>{});
    }, this.ts.trPK('general', 'settings'), () => {
    }, this.ts.trPK('general', 'cancel'), this.ts.trPK('vacation-rule', 'confirmation'), this.ts.trPK("general","forget-wifi-connection-text"));
    this.disconnectWifi();
  }

  async disconnectWifi() {
    const isAndroid = this.platform.is("android");
    const isIOS = this.platform.is("ios");
    if(isAndroid){
      await this.wifiWizard2.disconnect(this.ssid).catch((error)=>{ console.error(error) });
      await this.wifiWizard2.remove(this.ssid).catch((error)=>{ console.error(error) });
      console.debug("Wifi Removed");
    }else if(isIOS){
      await this.wifiWizard2.iOSDisconnectNetwork(this.ssid);
    }
  }

  async swipeAttendanceWifi(code:any) { 
      const isPlatformValue = this.platform.is('ios') ? 'WIFI-IOS' : 'WIFI-ANDROID';
      const enableFirestore = this.common.sharedService.getSharedData('enableFirestore', false);
 
      const request: attendanceSwipeScannerRequest = new attendanceSwipeScannerRequest();
      request.PointType = 3;
      request.Latitude = this.lat;
      request.Longitude = this.longt;
      request.QRValue = "";
      request.NFCValue = "";
      request.WifiValue =  "100";
      request.UID = this.device.uuid;
      request.UserName = this.userData.EMPLOYEE_NUMBER;
      request.IsGpsRequired = this.enableLocationWIFI;

      this.attendance_service
        .attendanceSwipeScanner(request, () => {
          if (enableFirestore) {
            this.failedObjectWIFI.userID = this.userData.EMPLOYEE_NUMBER;
            this.attendScanService.processFirebaseDocument(isPlatformValue, this.failedObjectWIFI);
          }
          this.closeModal();
          this.disconnectWifi();
        }).subscribe((result: Response) => {
          if (enableFirestore) {
            this.attendScanService.processFirebaseDocument(isPlatformValue, result);
          }
          // this.disconnectWifi();
          if (this.common.validResponse(result)) {
            if (result.MessageStatus && result.MessageStatus === 1) {
              this.ngZone.run(() => {
                this.gifStatus = true;
              });
              setTimeout(() => {
                this.closeModal();
              }, 4000);
              this.disconnectWifi();
            } else {
              if (enableFirestore) {
                this.failedObjectWIFI.userID = this.userData.EMPLOYEE_NUMBER;
                this.attendScanService.processFirebaseDocument(isPlatformValue, this.failedObjectWIFI);
              }
              this.disconnectWifi();
            }
          } else {
            if (enableFirestore) {
              this.failedObjectWIFI.userID = this.userData.EMPLOYEE_NUMBER;
              this.attendScanService.processFirebaseDocument(isPlatformValue, this.failedObjectWIFI);
            }
            this.disconnectWifi();
            this.closeModal();
          }
        });
  }

  public closeModal() {
    this.modalController.dismiss();
  }

  async isWifiAvailable(ssid:string){
    let avaialble_wifi = await this.wifiWizard2.scan(); 
    let find = avaialble_wifi.find(element => {
      return element.SSID == ssid;
    });
    
    if (find === undefined) {
      return false;
    } else {
      return find.SSID == ssid;
    }
  }
}
