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";


@Injectable({
  providedIn: 'root'
})
export class AttendScanService {
  location: boolean;
  camera: boolean;
  lat: any;
  longt: any;
  deviceID: string;
  scannedResult: any;
  userData: any = {};
  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,) {
          this.userData =this.common.sharedService.getSharedData(AuthenticatedUser.SHARED_DATA,false);
    }

    public getDeviceLocation() {
      let 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) {
          this.geolocation
            .getCurrentPosition({ maximumAge: 3000, timeout: 10000, enableHighAccuracy: true })
            .then(resp => {
            //  console.log(resp.coords.latitude);
             // console.log(resp.coords.longitude);
              this.lat = resp.coords.latitude;
              this.longt = resp.coords.longitude;
              this.attendance();
            })
            .catch(error => {
              console.log("Error getting location", error);
            });
       
        } else {
          return false;
        }
      });
  
    }
  
    public attendance() {
        this.permissions.requestCameraAutherization().then(granted => {
          this.camera = granted as boolean;
          if (this.camera) {
            this.scanCode();
          }
        }
        );
    }
  
  
    public scanCode() {
      this.barcodeScanner.scan().then(barcodeData => {
        console.log('Barcode data', barcodeData);
        // let strResult = JSON.parse(barcodeData);
        // console.log(strResult.QRValue);
        this.scannedResult = barcodeData;
        this.deviceID = this.device.uuid;
        this.swipeAttendance();
      }).catch(err => {
        console.log('Error', err);
      });
    }
  
  
    public swipeAttendance() {
      let request: attendanceSwipeScannerRequest = new attendanceSwipeScannerRequest();
      request.Latitude = this.lat;
      request.Longitude = this.longt;
      request.QRValue = this.scannedResult.text;
      request.UID = this.deviceID;
      request.UserName = this.userData.EMPLOYEE_NUMBER;
      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"));
          } else {
            this.common.presentAlert(this.ts.trPK("home", "swipeAlertFailed"));
          }
        });
    }
}
