import { Component, OnInit, NgZone, VERSION } from "@angular/core";
import { NFC } from "@ionic-native/nfc/ngx";
import { CommonService } from "src/app/hmg-common/services/common/common.service";
import { Platform } from "@ionic/angular";
import { AttendScanService } from "../../hmg-common/services/attend-services/attend-scan.service";
import { TranslatorService } from "src/app/hmg-common/services/translator/translator.service";
import { ModalController } from "@ionic/angular";
import { NfcModalComponent } from "../nfc-modal/nfc-modal.component";
import { WifiModalComponent } from "../wifi-model/wifi-modal.component";
import { AuthenticatedUser } from "../../hmg-common/services/authentication/models/authenticated-user";
import { AuthenticationService } from "src/app/hmg-common/services/authentication/authentication.service";
import { attendanceSwipeScannerRequest } from "src/app/home/models/attendanceSwipe.Request";
import { Device } from "@ionic-native/device/ngx";
import { AttendanceService } from "src/app/home/services/attendance.services";
import { Response } from "src/app/hmg-common/services/models/response";
import { WifiWizard2 } from "@ionic-native/wifi-wizard-2/ngx";
import { OpenNativeSettings } from '@ionic-native/open-native-settings/ngx';
import { DevicePermissionsService } from 'src/app/hmg-common/services/device-permissions/device-permissions.service';
import { Geolocation } from '@ionic-native/geolocation/ngx';
import { BackgroundGeolocation } from '@ionic-native/background-geolocation/ngx';
import { FirebaseX } from '@ionic-native/firebase-x/ngx';
import { HMGUtils } from 'src/app/hmg-common/hmg_utils';

declare var cordova: any;

@Component({
  selector: "app-attendance-options",
  templateUrl: "./attendance-options.component.html",
  styleUrls: ["./attendance-options.component.scss"],
})
export class AttendanceOptionsComponent implements OnInit {
  public location: boolean;
  public direction: string;
  public userData: any = {};
  public priviligeList: any;
  public serviceEnableNFC = false;
  public serviceEnableQR = false;
  public serviceEnableWifi = false;
  public enableLocationQR = false;
  public enableLocationNFC = false;
  public enableLocationWIFI = false;
  public enableFirestore = false;
  public deviceNFC = false;
  public nfcIOSSuccess = false;
  public lat = 0;
  public longt = 0;
  public isFakeLocationUsed = false;
  public deviceID: string;
  public firebasex: FirebaseX
  public isDocumentAvailable = false;
  public document: any;
  public check: any;


  constructor(
    private nfc: NFC,
    public common: CommonService,
    public platform: Platform,
    public attendScanService: AttendScanService,
    public ts: TranslatorService,
    public modalController: ModalController,
    private device: Device,
    private attendance_service: AttendanceService,
    public ngZone: NgZone,
    private wifiWizard2: WifiWizard2,
    private openNativeSettings: OpenNativeSettings,
    private devicePermissionsService:DevicePermissionsService,
    private geolocation: Geolocation,
    public backgroundGeolocation: BackgroundGeolocation,
    public hmgUtils: HMGUtils
  ) {}

  ngOnInit() {
    this.common.startLoading();
    this.direction = TranslatorService.getCurrentLanguageName();
    this.userData = this.common.sharedService.getSharedData(
      AuthenticatedUser.SHARED_DATA,
      false
    );
    this.priviligeList = AuthenticationService.servicePrivilage;
    this.setServicesPrivilage();
    this.checkNFCStatus("one");
  }

  public checkFirebaseDocument() {
    const id = this.userData.EMPLOYEE_NUMBER;
    this.attendScanService.checkFirestoreDocument(id);
  }

  async checkNFCStatus(checkValue: string) {
    try {
      let nfcStatus = await this.nfc.enabled();
      console.log("nfc status >>>>>>>>>>" + nfcStatus);
      if (nfcStatus === "NFC_OK") {
        this.deviceNFC = true;
        if (checkValue === "two") {
          this.startNFC();
        }
      }
      if (nfcStatus === null && checkValue === "two") {
        this.startNFC();
      }
    } catch (err) {
      console.log("Error reading tag", err);
      if (err === "NO_NFC") {
        this.deviceNFC = false;
      } else if (err === "NFC_DISABLED") {
        this.deviceNFC = true;
        if (checkValue === "two") {
          this.common.presentAlert(this.ts.trPK("general", "nfc-settings"));
        }
      } else if (checkValue === "two") {
        this.common.presentAlert(this.ts.trPK("general", "nfc-error"));
      }
    }
  }

  public setServicesPrivilage() {
    try {
      for (const servicePrivilage of AuthenticationService.servicePrivilage) {
        if (servicePrivilage.Previlege && servicePrivilage.ServiceName === "enableNFC") {
          this.serviceEnableNFC = true;
        }
        if (servicePrivilage.Previlege && servicePrivilage.ServiceName === "enableQR") {
          this.serviceEnableQR = true;
        }
        if (servicePrivilage.Previlege && servicePrivilage.ServiceName === "enableWIFI") {
          this.serviceEnableWifi = true;
        }
        if (servicePrivilage.Previlege && servicePrivilage.ServiceName === "enableLocationQR") {
          this.enableLocationQR = true;
        }
        if (servicePrivilage.Previlege && servicePrivilage.ServiceName === "enableLocationNFC") {
          this.enableLocationNFC = true;
        }
        if (servicePrivilage.Previlege && servicePrivilage.ServiceName === "enableLocationWIFI") {
          this.enableLocationWIFI = true;
        }
        
        if (servicePrivilage.Previlege && servicePrivilage.ServiceName === "enableFirestore") {
          this.enableFirestore = true;
          this.common.sharedService.setSharedData(true, 'enableFirestore');
          this.checkFirebaseDocument();
        } else {
          this.enableFirestore = false;
          this.common.sharedService.setSharedData(false, 'enableFirestore');
          this.common.stopLoading();
        }
      }
    } catch (error) {
      console.log(error);
      this.common.stopLoading();
    }
  }

  async startIOSNfc() {
    try {
      let tag = await this.nfc.scanTag();
      console.log(JSON.stringify(tag));
      const serialNumber = this.nfc.bytesToHexString(tag.id);
      this.swipeAttendanceNFC(serialNumber);
    } catch (err) {
      this.common.presentAlert(this.ts.trPK("general", "nfc-error"));
      console.log("Error reading tag", err);
    }
  }

  public async nfcModal() {
    const modal = await this.modalController.create({
      component: NfcModalComponent,
      showBackdrop: true,
      backdropDismiss: true,
      componentProps:{ enableLocationNFC: this.enableLocationNFC, lat: this.lat, longt: this.longt},
    });
    modal.cssClass = "nfc-modal";
    await modal.present();
  }

  public swipeAttendanceNFC(nfcSerialCode: any) {
    const request: attendanceSwipeScannerRequest = new attendanceSwipeScannerRequest();
    request.PointType = 2;
    request.Latitude = this.lat;
    request.Longitude = this.longt;
    request.QRValue = "";
    request.NFCValue = nfcSerialCode;
    request.UID = this.device.uuid;
    request.UserName = this.userData.EMPLOYEE_NUMBER;
    request.IsGpsRequired = this.enableLocationNFC;
    this.attendance_service
      .attendanceSwipeScanner(request, () => {
        console.log("Error inside in swipe attendance");
      })
      .subscribe((result: Response) => {
        if (this.enableFirestore) {
          this.attendScanService.processFirebaseDocument('NFC-IOS', result);
        }
        if (this.common.validResponse(result)) {
          this.ngZone.run(() => {
            this.nfcIOSSuccess = true;
          });
          setTimeout(() => {
            this.common.openHome();
          }, 4000);
        }
      });
  }

  public startNFC() {
    const isAndroid = this.platform.is("android");
    const isIOS = this.platform.is("ios");
    if (isAndroid) {
      this.nfcModal();
    } else if (isIOS) {
      this.startIOSNfc();
    }
  }

  public startQRCode() {
    if (this.enableLocationQR) {
      this.attendScanService.getDeviceLocation();
    } else {
      this.attendScanService.attendance(false);
    }
  }

  public startNFCCode() {
    if (this.enableLocationNFC) {
      this.getDeviceLocation('NFC');
    } else {
      this.checkNFCStatus('two');
    }
  }

  public startWIFICode() {
    if (this.enableLocationWIFI) {
      this.getDeviceLocation('WIFI');
    } else {
      this.startWifi();
    }
  }

  // Wifi Attendance
  public async startWifi() {
    const isAndroid = this.platform.is("android");
    const isIOS = this.platform.is("ios");
    const isWifiEnabled = await this.wifiWizard2.isWifiEnabled();
    const versionType = this.device.version;
    const versionTypeInt = parseInt(versionType);
    console.log('version type: ' + versionType);
    console.log('version Type: ' + versionTypeInt);
    
    if(isAndroid && versionTypeInt > 10) {
      if(!isWifiEnabled){
        this.showWifiNotEnabled();
        return;
      }
    }

    if (isIOS) {
      if(!isWifiEnabled){
        this.showWifiNotEnabled();
        return;
      }
    } else if(isAndroid) {
      let locationPermission = await this.devicePermissionsService.requestLocationAutherization();
      if (!locationPermission) {
        return;
      }

      if(!isWifiEnabled){
        this.wifiWizard2.setWifiEnabled(true).then(()=>{
          this.startWifi();
        }).catch((err) => { 
          console.debug(err);
        });
        return;
    }
  }
  // opening wifi dailog if all above conditions are passed (isWifiEnabled == true)
  let modal = await this.modalController.create({
    component: WifiModalComponent,
    showBackdrop: true,
    backdropDismiss: false,
    componentProps:{ enableLocationWIFI: this.enableLocationWIFI, lat: this.lat, longt: this.longt}
  });
  modal.cssClass = "wifi-modal";
  await modal.present();
}



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

public getDeviceLocation(source: string) {
    try {
      this.hmgUtils.getCurrentLocation((resp) => {
        console.log(resp);
        if (resp) {
          this.isFakeLocationUsed = resp.isfake;
          this.lat = resp.latitude;
          this.longt = resp.longitude;
          
          if (this.isFakeLocationUsed) {
            this.fakeSwipeAttendance(source);
          } else {
            this.lat = resp.latitude;
            this.longt = resp.longitude;
            if (source === 'WIFI') {
              this.startWifi();
            } else if (source === 'NFC') {
              this.checkNFCStatus('two');
            }   
          }
        }
      });
    } catch (e) {
      this.common.presentAlert(this.ts.trPK('general', 'something-went-wrong'));
    }

    // this.isFakeLocationUsed = false;
    // this.devicePermissionsService.requestLocationAutherization().then(granted => {
    //   this.location = granted as boolean;
    //   if (this.location) {
    //     if (this.platform.is('android')) {
    //       this.backgroundGeolocation.getCurrentLocation({ timeout: 10000, enableHighAccuracy: true, maximumAge: 3000 }).then((resp) => {
    //         if (resp && (resp.latitude && resp.longitude)) {
    //           if (resp.isFromMockProvider || resp.mockLocationsEnabled) {
    //             this.isFakeLocationUsed = true;
    //             this.fakeSwipeAttendance(source);
    //           } else {
    //             this.lat = resp.latitude;
    //             this.longt = resp.longitude;
    //             if (source === 'WIFI') {
    //               this.startWifi();
    //             } else if (source === 'NFC') {
    //               this.checkNFCStatus('two');
    //             }   
    //           }
    //         } else {
    //           this.common.presentAlert(this.ts.trPK('home', 'position-error'));
    //         }
    //       }, (error) => {
    //             this.common.presentAlert(this.ts.trPK('home', 'position-error'));
    //       });
    //     } else {
    //       this.geolocation.getCurrentPosition({maximumAge: 3000, timeout: 10000, enableHighAccuracy: true}).then(resp => {
    //         if(resp && resp.coords.latitude && resp.coords.longitude) {
    //           this.lat = resp.coords.latitude;
    //           this.longt = resp.coords.longitude;
    //           if (source === 'WIFI') {
    //             this.startWifi();
    //           } else if (source === 'NFC') {
    //             this.checkNFCStatus('two');
    //           }
    //         } else {
    //           this.common.presentAlert(this.ts.trPK('home', 'position-error'));
    //         }
    //       }).catch(error => {
    //         this.common.presentAlert(this.ts.trPK('home', 'position-error'));
    //       });
    //     } 
    //   } else {
    //     return false;
    //   }
    // });
  }

  public fakeSwipeAttendance(sourceName: string) {
    const request: any = {};
    request.Latitude = this.lat;
    request.Longitude = this.longt;
    request.QRValue = '';
    request.NFCValue = sourceName === 'NFC' ? sourceName : '';
    request.WifiValue = sourceName === 'WIFI' ? sourceName : '';
    request.UID = this.deviceID;
    request.EmployeeID = this.userData.EMPLOYEE_NUMBER;
    this.attendance_service.fakeAttendanceSwipeScanner(request, () => {console.log('Error inside in swipe attendance');})
      .subscribe((result: Response) => {
        if (this.common.validResponse(result)) {
            this.common.presentAlert(this.ts.trPK('home', 'fake-location'));
        }
    });
  }

}
