import { Injectable } from '@angular/core';
// import { DevicePermissionsService } from '../device-permissions/device-permissions.service';
import { DomSanitizer } from '@angular/platform-browser';
import { SharedDataService } from '../shared-data-service/shared-data.service';
import { BarcodeScanner } from '@ionic-native/barcode-scanner/ngx';
import { AttendanceService } from 'src/app/home/services/attendance.services';
import { ZBar } from '@ionic-native/zbar/ngx';
import { Geolocation } from '@ionic-native/geolocation/ngx';
import { attendanceSwipeScannerRequest } from 'src/app/home/models/attendanceSwipe.Request';
import { AuthenticatedUser } from '../authentication/models/authenticated-user';
import { CommonService } from '../common/common.service';
import { TranslatorService } from '../translator/translator.service';
import { Response } from 'src/app/hmg-common/services/models/response';
import { Camera, CameraOptions, PictureSourceType} from '@ionic-native/Camera/ngx';
import { DevicePermissionsService } from '../../services/device-permissions/device-permissions.service';
import { Device } from '@ionic-native/device/ngx';
import { BackgroundGeolocation } from '@ionic-native/background-geolocation/ngx';
import { Platform } from '@ionic/angular';
import { ModalController } from '@ionic/angular';


@Injectable({
  providedIn: 'root'
})
export class AttendScanService {
  location: boolean;
  camera: boolean;
  lat = 0;
  longt = 0;
  deviceID: string;
  scannedResult: any;
  userData: any = {};
  public isFakeLocationUsed = false;
  public isGpsRequired = false;

  constructor(private device: Device,
              private zbar: ZBar,
              private geolocation: Geolocation,
              private attendance_service: AttendanceService,
              private barcodeScanner: BarcodeScanner,
              private cameraController: Camera,
              public sharedData: SharedDataService,
              private sanitizer: DomSanitizer,
              private permissions: DevicePermissionsService,
              public common: CommonService,
              public ts: TranslatorService,
              public backgroundGeolocation: BackgroundGeolocation,
              public platform: Platform,
              public modalController: ModalController
            ) {
          this.userData = this.common.sharedService.getSharedData(AuthenticatedUser.SHARED_DATA, false);
    }

    getDeviceLocation() {
      this.isGpsRequired = true;
      this.isFakeLocationUsed = false;
      const isVirtual = this.device.isVirtual;
      if (isVirtual === true) {
        alert('emulater>>>>>>>' + isVirtual);
        alert('You are using virtual device');
        return false;
      }
      this.permissions.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.lat = resp.latitude;
                this.longt = resp.longitude;
                this.attendance(true);
                
              } 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;
                this.attendance(true);

              } 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 attendance(isGPSValue: boolean) {
      this.isGpsRequired = isGPSValue;
      if (!this.isGpsRequired) {
        this.lat = 0;
        this.longt = 0;
      }
      this.permissions.requestCameraAutherization().then(granted => {
        this.camera = granted as boolean;
        if (this.camera) {
          this.scanCode();
        }
      });
    }

    scanCode() {
      this.barcodeScanner
        .scan()
        .then(barcodeData => {
          if (!barcodeData.cancelled) {
            this.scannedResult = barcodeData;
            this.deviceID = this.device.uuid;
            if (this.isFakeLocationUsed) {
              this.fakeSwipeAttendance();
            } else {
              this.swipeAttendance();
            }
          }
        })
        .catch(err => {
          console.log('Error', err);
        });
    }

    fakeSwipeAttendance() {
      const request: any = {};
      request.Latitude = this.lat;
      request.Longitude = this.longt;
      request.QRValue = this.scannedResult.text;
      request.NFCValue = '';
      request.WIFIValue = '';
      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'));
          }
      });
    }


    public swipeAttendance() {
      const request: attendanceSwipeScannerRequest = new attendanceSwipeScannerRequest();
      request.PointType = 1;
      request.Latitude = this.lat;
      request.Longitude = this.longt;
      request.QRValue = this.scannedResult.text;
      request.NFCValue = '';
      request.UID = this.deviceID;
      request.UserName = this.userData.EMPLOYEE_NUMBER;
      request.IsGpsRequired = this.isGpsRequired;
      console.log('request');
      console.log(JSON.stringify(request));
      this.attendance_service
        .attendanceSwipeScanner(request, () => {
          console.log('Error inside in swipe attendance');
        })
        .subscribe((result: Response) => {
          if (this.common.validResponse(result)) {
            console.log('response');
            console.log(result);
            this.common.presentAlert(this.ts.trPK('home', 'swipeAlertSuccess'));
            this.common.openHome();
          }
        });
    }

    // public swipeAttendanceNFC (nfcSerialCode: any) {
    //   const request: attendanceSwipeScannerRequest = new attendanceSwipeScannerRequest();
    //   request.PointType = 2;
    //   request.Latitude = 0;
    //   request.Longitude = 0;
    //   request.QRValue = "";
    //   request.NFCValue = nfcSerialCode;
    //   request.UID = this.device.uuid;
    //   request.UserName = this.userData.EMPLOYEE_NUMBER;
    //   this.attendance_service.attendanceSwipeScanner(request, () => {
    //       console.log('Error inside in swipe attendance');
    //     }).subscribe((result: Response) => {
    //       if (this.common.validResponse(result)) {
    //         this.modalController.dismiss();

    //       }
    //     });
    // }
}
