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';
import { FirebaseX } from '@ionic-native/firebase-x/ngx';
import { HMGUtils } from 'src/app/hmg-common/hmg_utils';


@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;
  public collection = 'CS';

  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,
              public firebasex: FirebaseX,
              public hmgUtils: HMGUtils
            ) {
          this.userData = this.common.sharedService.getSharedData(AuthenticatedUser.SHARED_DATA, false);
          console.log(this.userData);
    }

    public 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;
      }
      //////////// Getting location from hmg_utils //////////////////
      try {
        this.hmgUtils.getCurrentLocation((resp) => {
          console.log(resp);
          if (resp) {
            this.isFakeLocationUsed = resp.isfake;
            this.lat = resp.latitude;
            this.longt = resp.longitude;
            this.attendance(true);
          }
        });
      } catch (e) {
        this.common.presentAlert(this.ts.trPK('general', 'something-went-wrong'));
      }

      // 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 async checkFirestoreDocument(userID : string) {
      try {
        let result = {};
        await this.firebasex.fetchDocumentInFirestoreCollection(userID, this.collection, (document: any) => {
          console.log("Successfully Fetched the document with id =" + userID);
          result = {
            isDocumentAvailable: true,
            document: document 
          };
          this.common.sharedService.setSharedData(result, 'firebase-document');
          this.common.stopLoading();
        }, (error: any) => {
          console.log(error);
          result = {
            isDocumentAvailable: false,
            document: null 
          };
          this.common.sharedService.setSharedData(result, 'firebase-document');
          this.common.stopLoading();
        })
      } catch(error) {
        console.log(error);
        const result = {
          isDocumentAvailable: false,
          document: null 
        };
        this.common.sharedService.setSharedData(result, 'firebase-document');
        this.common.stopLoading();
      }
    }

    public updateFirebaseDocument(resultObject: any) {
      try {
        let currentFirebaseDocument = this.common.sharedService.getSharedData('firebase-document', false);
        let currentSwipeArray = currentFirebaseDocument.document.swipeData;
        if (currentSwipeArray) {
          currentSwipeArray.push(resultObject);
        } else {
          let swipeData = [];
          swipeData.push(resultObject);
          currentSwipeArray = swipeData;
        }
        const updatedDocument = {
          swipeData: currentSwipeArray
        };
        console.log(updatedDocument);
        this.firebasex.updateDocumentInFirestoreCollection(this.userData.EMPLOYEE_NUMBER, updatedDocument, this.collection, () => {
          console.log("Successfully updated document with id = " + this.userData.EMPLOYEE_NUMBER);
          const result = {
            isDocumentAvailable: true,
            document: updatedDocument 
          };
          this.common.sharedService.setSharedData(result, 'firebase-document');
        }, (error) => {
          console.error("Error adding document: " + error);
        });
      } catch (error) {
        console.log(error);
      }
    }

    public checkDocumentAvailability(resultObject: any) {
      const firestoreDocument = this.common.sharedService.getSharedData('firebase-document', false);
      if (firestoreDocument) {
        if (firestoreDocument.isDocumentAvailable) {
          this.updateFirebaseDocument(resultObject);
        } else {
          this.createNewDocument(resultObject);
        }
      } else {
        this.createNewDocument(resultObject);
      }
    }

    public processFirebaseDocument(mode: string, result: any) { 
      try {
        this.userData = this.common.sharedService.getSharedData(AuthenticatedUser.SHARED_DATA, false);
        const resultObject = {
          modeOfAttendance: mode,
          messageStatus: result.MessageStatus,
          transactionID: result.SWP_AuthenticateAndSwipeUserModel.TransactionID,
          userID: result.SWP_AuthenticateAndSwipeUserModel.UserID,
          pointID: result.SWP_AuthenticateAndSwipeUserModel.PointID,
          branchDescription: result.SWP_AuthenticateAndSwipeUserModel.BranchDescription
        }
        this.checkDocumentAvailability(resultObject);
      } catch (error) {
        console.log(error);
      }    
    }

    public createNewDocument(resultObject: any) {
      let swipeData = [];
      swipeData.push(resultObject);
      const newDocument = {
        swipeData: swipeData
      };
      this.firebasex.setDocumentInFirestoreCollection(this.userData.EMPLOYEE_NUMBER, newDocument, this.collection, () => {
        console.log("Successfully added document"); 
        const result = {
          isDocumentAvailable: true,
          document: newDocument 
        };
        this.common.sharedService.setSharedData(result, 'firebase-document');
      }, (error) => {
        console.error("Error adding document: "+error);
      });
    } 

    public swipeAttendance() {
      const isPlatformValue = this.platform.is('ios') ? 'QR-IOS' : 'QR-ANDROID';
      const enableFirestore = this.common.sharedService.getSharedData('enableFirestore', false);

      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 (enableFirestore) {
            this.processFirebaseDocument(isPlatformValue, result);
          }
          if (this.common.validResponse(result)) {
            console.log('response');
            console.log(result);
            this.common.presentAlert(this.ts.trPK('home', 'swipeAlertSuccess'));
            this.common.openHome();
          }
        });
    }
}
