import { Injectable } from "@angular/core";
import { BackgroundGeolocation } from '@ionic-native/background-geolocation/ngx';
import { CommonService } from "src/app/hmg-common/services/common/common.service";
import { TranslatorService } from "src/app/hmg-common/services/translator/translator.service";
import { DevicePermissionsService } from 'src/app/hmg-common/services/device-permissions/device-permissions.service';
import { Geolocation } from '@ionic-native/geolocation/ngx';
import { Platform } from "@ionic/angular";

declare const cordova: any;

@Injectable({
    providedIn: 'root'
})
export class HMGUtils {
    constructor(
        public backgroundGeolocation: BackgroundGeolocation,
        public common: CommonService,
        public ts: TranslatorService,
        private geolocation: Geolocation,
        public platform: Platform,
        public devicePermissionsService:DevicePermissionsService,
    ) { }

    async getCurrentLocation(callBack: Function) {
        
        this.devicePermissionsService.requestLocationAutherization().then( async granted => {
            if(granted == true) {
                if (this.platform.is('android')) {
                    if ((await this.isHuaweiDevice())) {
                        this.getHMSLocation(callBack);
                    } else {
                        this.getGMSLocation(callBack);
                    }
                } else {
                    this.getIOSLocation(callBack);
                }
            } else {
                return false;
            }
        });

    }


    async isHuaweiDevice(): Promise<boolean> {
        const result: any = await new Promise((resolve, reject) => {
            cordova.plugins.CordovaHMSGMSCheckPlugin.isHmsAvailable(
                "index.js",
                (_res) => {
                    const hmsAvailable = _res === "true";
                    resolve(hmsAvailable);
                },
                (_err) => {
                    reject({ "status": false, "error": JSON.stringify(_err) });
                    this.common.presentAlert(this.ts.trPK('general', 'huawei-hms-gms-error'));
                }
            );
        });

        return result;
    }

    private getHMSLocation(callBack: Function) {
        try {
            cordova.plugins.CordovaHMSLocationPlugin.requestLocation(
                "index.js",
                (_res) => {
                    console.log("Huawei Location Success: [Stop Getting]");
                    cordova.plugins.CordovaHMSLocationPlugin.removeLocation("", (_res) => { }, (_err) => { });
                    const location = _res.split(',')
                    console.log(location);
                    if (location.length == 3) {
                        let mock = false;
                        const lat = Number(_res.split(',')[0]);
                        const long = Number(_res.split(',')[1]);
                        const mockValue = _res.split(',')[2];
                        
                        if (mockValue == 'true') {
                            mock = true;
                        } else {
                            mock = false;
                        }
                        callBack({"latitude":lat, "longitude":long, "isfake":mock})
                    } else {
                        this.common.presentAlert(this.ts.trPK('general', 'invalid-huawei-location'));
                    }
                },
                (_err) => {
                    console.log("Huawei Location [Getting Error]: " + JSON.stringify(_err));
                    this.common.presentAlert(this.ts.trPK('general', 'invalid-huawei-location'));
                }
            );

        } catch (_err) {
            console.log("Huawei Location Plugin [Error]: " + + JSON.stringify(_err));
            this.common.presentAlert(this.ts.trPK('general', 'huawei-plugin-issue'));
        }
    }

    private getGMSLocation(callBack: Function) {
        this.backgroundGeolocation.getCurrentLocation({ timeout: 10000, enableHighAccuracy: true, maximumAge: 3000 }).then((resp) => {
            if (resp && (resp.latitude && resp.longitude)) {
                const isFakeLocation = resp.isFromMockProvider || resp.mockLocationsEnabled;
                const lat = resp.latitude;
                const long = resp.longitude;
                callBack({"latitude":lat, "longitude":long, "isfake":isFakeLocation})
            } else {
                this.common.presentAlert(this.ts.trPK('home', 'position-error'));
            }
        }, (error) => {
            this.common.presentAlert(this.ts.trPK('home', 'position-error'));
        });
    }

    private getIOSLocation(callBack: Function) {
        this.geolocation.getCurrentPosition({ maximumAge: 3000, timeout: 10000, enableHighAccuracy: true }).then(resp => {
            if (resp && resp.coords.latitude && resp.coords.longitude) {
                const lat = resp.coords.latitude;
                const long = resp.coords.longitude;
                callBack({"latitude":lat, "longitude":long, "isfake":false})
            } else {
                this.common.presentAlert(this.ts.trPK('home', 'position-error'));
            }
        }).catch(error => {
            this.common.presentAlert(this.ts.trPK('home', 'position-error'));
        });
    }


}