import { HttpClient } from '@angular/common/http';
import { Inject, Injectable, PLATFORM_ID } from '@angular/core';
import { CommonService } from './common.service';
import { GlobalService } from './global.service';
// import {} from '@types/googlemaps';

@Injectable({
    providedIn: 'root'
})
export class VisitorsService {
    public lat: any
    public log: any;
    public that = this;

    constructor(
        private http: HttpClient,
        private commonService: CommonService,
        private globalService: GlobalService,
        @Inject(PLATFORM_ID) public platformId: object
    ) {

    }
    getPosition() {
        let res = new Promise((resolve, reject) => {
            navigator.geolocation?.getCurrentPosition(resp => {
                resolve({ lng: resp.coords.longitude, lat: resp.coords.latitude });
                this.lat = resp.coords.latitude;
                this.log = resp.coords.longitude;
                console.log(resp.coords.latitude, resp.coords.longitude, this.lat, this.log);
                this.getCity(this.lat, this.log)

                // let url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + this.lat + "," + this.log + "&key=AIzaSyBKCmakmDoWZdP6H6lIFJsBOBYyPdslQ4s";
                // let res1 = this.http.get(url);
                // res1 = JSON.parse(JSON.stringify(res1));
                // console.log(res1, url);

            },
                err => {
                    reject(err);
                });
        });
        console.log(this.lat);
    }
    // getCity(lat, long) {
    //     let that = this;
    //     var xhr = new XMLHttpRequest();
    //     var lat = lat;
    //     var lng = long;
    //     // var lat: any = 30.7143;
    //     // var lng = 76.7011;

    //     // Paste your LocationIQ token below.
    //     xhr.open('GET', "https://us1.locationiq.com/v1/reverse.php?key=pk.248c89d1b557fe204ce29bf38313a357&lat=" + lat + "&lon=" + lng + "&format=json", true);
    //     xhr.send();
    //     xhr.onreadystatechange = processRequest;
    //     xhr.addEventListener("readystatechange", processRequest, false);

    //     async function processRequest(e: { target: { value: any; }; length: number; }) {
    //         if (xhr.readyState == 4 && xhr.status == 200) {
    //             let DB_cities = await that.commonService.getCitites()
    //             var response = JSON.parse(xhr.responseText);
    //             var city;
    //             let ind = response.address.village ? DB_cities.findIndex(c => c.name.toLowerCase().includes(response.address.village.toLowerCase())) : -1;
    //             if (ind >= 0) {
    //                 city = response.address.village.toLowerCase();
    //             } else {
    //                 ind = response.address.town ? DB_cities.findIndex(c => c.name.toLowerCase().includes(response.address.town.toLowerCase())) : -1;
    //                 if (ind >= 0) {
    //                     city = response.address.town.toLowerCase();
    //                 } else {
    //                     ind = response.address.city ? DB_cities.findIndex(c => c.name.toLowerCase().includes(response.address.city.toLowerCase())) : -1;
    //                     if (ind >= 0) {
    //                         city = response.address.city.toLowerCase();
    //                     } else {
    //                         if (response.address.county && response.address.county.toLowerCase().includes("tehsil")) {
    //                             response.address.county = response.address.county.toLowerCase().replaceAll("tehsil", "").trim();//.replace(" ", "-");
    //                         }
    //                         if (response.address.county && response.address.county.toLowerCase().includes("tahsil")) {
    //                             response.address.county = response.address.county.toLowerCase().replaceAll("tahsil", "").trim();//.replace(" ", "-");
    //                         }
    //                         if (response.address.county && response.address.county.toLowerCase().includes("taluka")) {
    //                             response.address.county = response.address.county.toLowerCase().replaceAll("taluka", "").trim();//.replace(" ", "-");
    //                         }
    //                         ind = response.address.county ? DB_cities.findIndex(c => c.name.toLowerCase().includes(response.address.county.toLowerCase())) : -1;
    //                         if (ind >= 0) {
    //                             city = response.address.county.toLowerCase();
    //                         } else {
    //                             // ind = DB_cities.findIndex(c => c.name.toLowerCase().includes(response.address.state_district.toLowerCase));
    //                             // if (ind >= 0) {
    //                             city = response.address.state_district ? response.address.state_district.toLowerCase() : (response.address.district ? response.address.district : "surat");
    //                             // } else {

    //                             // }
    //                         }
    //                     }
    //                 }
    //             }
    //             // city = city ? city : response.address.village;
    //             // city = city ? city : response.address.town;
    //             // city = city ? city : response.address.city;
    //             // city = city ? city : response.address.county;

    //             if (city) {
    //                 if (city.toLowerCase().includes("tehsil")) {
    //                     city = city.toLowerCase().replaceAll("tehsil", "").trim().replaceAll(" ", "-");
    //                 }
    //                 if (city.toLowerCase().includes("tahsil")) {
    //                     city = city.toLowerCase().replaceAll("tahsil", "").trim().replaceAll(" ", "-");
    //                 }
    //                 if (city.toLowerCase().includes("taluka")) {
    //                     city = city.toLowerCase().replaceAll("taluka", "").trim().replaceAll(" ", "-");
    //                 }
    //                 if (city.toLowerCase().includes("district")) {
    //                     city = city.toLowerCase().replaceAll("district", "").trim().replaceAll(" ", "-");
    //                 }
    //                 if (city.toLowerCase().indexOf(" ") >= 0) {
    //                     city = city.toLowerCase().trim().replaceAll(" ", "-");
    //                 }
    //                 if (city.toLowerCase().indexOf("(") >= 0) {
    //                     city = city.toLowerCase().trim().replaceAll("(", "");
    //                 }
    //                 if (city.toLowerCase().indexOf(")") >= 0) {
    //                     city = city.toLowerCase().trim().replaceAll(")", "");
    //                 }
    //             }
    //             console.log("Getting City=>" + city);
    //             if (isPlatformBrowser(that.platformId)) {
    //                 if (city) {
    //                     //#region Gujarat
    //                     if (city == "tapi")
    //                         city = "vyara";
    //                     if (city == "narmada")
    //                         city = "rajpipla";
    //                     if (city == "sabarkantha")
    //                         city = "himatnagar";
    //                     if (city == "panchmahal")
    //                         city = "godhra";
    //                     if (city == "kutch")
    //                         city = "bhuj";
    //                     if (city == "mahisagar")
    //                         city = "lunavada";
    //                     if (city == "kheda")
    //                         city = "nadiad";
    //                     if (city == "devbhumi-dwarka")
    //                         city = "khambhalia";
    //                     if (city == "banaskantha")
    //                         city = "palanpur";
    //                     if (city == "aravalli")
    //                         city = "modasa";
    //                     //#endregion Gujarat
    //                     //#region AP
    //                     if (city == "east-godavari")
    //                         city = "kakinada";
    //                     if (city == "ysr")
    //                         city = "kurnool";
    //                     if (city == "krishna")
    //                         city = "machilipatnam";
    //                     if (city == "prakasam")
    //                         city = "ongole";
    //                     if (city == "sri-potti-sriramulu-nellore")
    //                         city = "nellore";
    //                     if (city == "west-godavari")
    //                         city = "bheemavaram";
    //                     //#endregion AP
    //                     //#region AR
    //                     if (city == "dibang-valley")
    //                         city = "roing";
    //                     if (city == "east-kameng")
    //                         city = "seppa";
    //                     if (city == "east-siang")
    //                         city = "pasighat";
    //                     if (city == "lohit")
    //                         city = "namsai";
    //                     if (city == "lower-subansiri")
    //                         city = "ziro";
    //                     if (city == "papum-pare")
    //                         city = "itanagar";
    //                     if (city == "tirap")
    //                         city = "deomali";
    //                     if (city == "upper-subansiri")
    //                         city = "daporijo";
    //                     if (city == "west-kameng")
    //                         city = "bomdila";
    //                     if (city == "west-siang")
    //                         city = "along";
    //                     //#endregion AR
    //                     //#region Assam
    //                     if (city == "cachar")
    //                         city = "silchar";
    //                     if (city == "darrang")
    //                         city = "mangaldoi";
    //                     if (city == "kamrup")
    //                         city = "guwahati";
    //                     if (city == "karbi-anglong")
    //                         city = "diphu";
    //                     if (city == "lakhimpur")
    //                         city = "north-lakhimpur";
    //                     if (city == "north-cachar-hills")
    //                         city = "haflong";
    //                     if (city == "sonitpur")
    //                         city = "tezpur";
    //                     //#endregion Assam
    //                     //#region Bihar
    //                     if (city == "east-champaran" || city == "purba-champaran")
    //                         city = "Motihari";
    //                     if (city == "baimur")
    //                         city = "bhabua";
    //                     if (city == "nalanda")
    //                         city = "bihar";
    //                     if (city == "west-champaran" || city == "pashchim-champaran")
    //                         city = "bettiah";
    //                     if (city == "rohtas")
    //                         city = "sasaram";
    //                     if (city == "saran")
    //                         city = "chapra";
    //                     if (city == "vaishali")
    //                         city = "hajipur";
    //                     //#endregion Bihar
    //                     //#region 36gadh
    //                     if (city == "bastar")
    //                         city = "jagdalpur";
    //                     if (city == "jashpur")
    //                         city = "jashpur-nagar";
    //                     if (city == "surguja")
    //                         city = "ambikapur";
    //                     //#endregion 36gadh
    //                     //#region Goa
    //                     if (city == "north-goa")
    //                         city = "panaji";
    //                     if (city == "south-goa")
    //                         city = "margao";
    //                     //#endregion Goa
    //                     //#region Delhi
    //                     if (city == "central-delhi")
    //                         city = "new-delhi-municipal-council";
    //                     if (city == "east-delhi")
    //                         city = "dallo-pura";
    //                     if (city == "new-delhi")
    //                         city = "new-delhi";
    //                     if (city == "north-delhi")
    //                         city = "jharoda-majra-burari";
    //                     if (city == "north-east-delhi")
    //                         city = "babarpur";
    //                     if (city == "north-west-delhi")
    //                         city = "alipur";
    //                     if (city == "south-delhi")
    //                         city = "deoli";
    //                     if (city == "south-west-delhi")
    //                         city = "delhi-cantt";
    //                     if (city == "west-delhi")
    //                         city = "nangloi-jat";
    //                     //#endregion Delhi
    //                     let selectedCity = sessionStorage.getItem("selectedCity");
    //                     if (selectedCity == "surat")
    //                         sessionStorage.setItem("selectedCity", city.toLowerCase());
    //                     else if (!selectedCity)
    //                         sessionStorage.setItem("selectedCity", city.toLowerCase());
    //                     else if (city != selectedCity)
    //                         sessionStorage.setItem("selectedCity", city.toLowerCase());
    //                     else {
    //                         sessionStorage.setItem("selectedCity", city.toLowerCase());
    //                     }
    //                 } else {
    //                     sessionStorage.setItem("selectedCity", "surat");
    //                 }
    //             }
    //             return city;
    //         }
    //     }
    // }

    public async getCity(latitude: any, longitude: any) {
        try {
            let city: string;
            let res = await this.globalService.getTowns(latitude, longitude);
            if (res && res.recordList) {
                if (res.recordList[0].distance <= 100) {
                    city = res.recordList[0].name;
                    sessionStorage.setItem("selectedCity", city.toLowerCase());
                } else {
                    sessionStorage.setItem("selectedCity", "");
                }
            }
        } catch (error: any) {
            let err;
            if (error && error.error && error.error.message) {
                err = error.error.message
            }
            else if (error && error.message) {
                err = error.message
            }
            console.log(err);

        }
    }
}
