import { Geolocation } from "@ionic-native/geolocation";
import { Component, Prop, h, Build, State, Method, Listen, } from "@stencil/core";
import algoliasearch from "algoliasearch";
import zipCodeLookup from "../../../helpers/zipCodeLookup";
export class LocationBar {
  constructor() {
    this.algoliaAppId = "ZKFP93O6EH";
    this.algoliaSearchKey = "cef2b52143823594c9c5af78ad86bcf0";
    this.algoliaIndex = "locations";
    this.endOfSearch = false;
    this.searchOptions = {};
    this.searchResults = [];
    this.resultCount = 0;
    this.searchResultPages = 0;
    this.changingLocation = false;
  }
  async findLocation(id) {
    this.location = await this.index.getObject(id);
    return this.location;
  }
  async search(query, options) {
    return this.index.search(query, {
      ...options,
      facetFilters: [["isSearchable:true"]],
    });
  }
  onInput(event) {
    var _a;
    if (((_a = event.target) === null || _a === void 0 ? void 0 : _a.name) !== "query")
      return;
    this.query = event.target.value;
  }
  getLocationCoords(callback) {
    try {
      Geolocation.getCurrentPosition()
        .then((position) => {
        if (callback && typeof callback === "function") {
          callback(position.coords);
        }
      })
        .catch(async (error) => {
        console.log(error);
        fetch("http://ip-api.com/json").then(async (response) => {
          const ISPInfo = await response.json();
          callback({
            latitude: ISPInfo.lat,
            longitude: ISPInfo.lon,
          });
        });
        if (callback && typeof callback === "function") {
          callback(false);
        }
      });
    }
    catch (error) {
      callback(false);
    }
  }
  changeLocation() {
    const zipCode = zipCodeLookup(this.query);
    this.position = {
      latitude: zipCode === null || zipCode === void 0 ? void 0 : zipCode.lat,
      longitude: zipCode === null || zipCode === void 0 ? void 0 : zipCode.lng,
    };
    this.resetSearchOptions();
    this.search("", this.searchOptions)
      .then((response) => {
      var _a;
      this.searchResultPages = parseInt(response.nbPages, 10);
      this.searchResults = response.hits;
      this.resultCount = response.nbHits;
      this.location = (_a = this.searchResults) === null || _a === void 0 ? void 0 : _a[0];
    })
      .catch((error) => {
      console.log(error.message);
    });
    this.changingLocation = false;
  }
  resetSearchOptions() {
    this.query = "";
    this.endOfSearch = false;
    this.searchOptions = this.searchOptions ? this.searchOptions : {};
    this.searchOptions.page = 0;
    if (this.position) {
      this.searchOptions.aroundLatLng = `${this.position.latitude},${this.position.longitude}`;
    }
  }
  async componentDidLoad() {
    if (!(Build === null || Build === void 0 ? void 0 : Build.isBrowser))
      return;
    const client = algoliasearch(this.algoliaAppId, this.algoliaSearchKey);
    this.index = client.initIndex(this.algoliaIndex);
    setTimeout(async () => {
      this.getLocationCoords((coords) => {
        this.position = coords
          ? { latitude: `${coords.latitude}`, longitude: `${coords.longitude}` }
          : { latitude: "38.6270025", longitude: "-90.19940419999999" };
        this.resetSearchOptions();
        this.search(this.query || "", this.searchOptions)
          .then((response) => {
          var _a;
          this.searchResultPages = parseInt(response.nbPages, 10);
          this.searchResults = response.hits;
          this.resultCount = response.nbHits;
          this.location = (_a = this.searchResults) === null || _a === void 0 ? void 0 : _a[0];
        })
          .catch((error) => {
          console.log(error.message);
        });
      });
    }, 100);
  }
  render() {
    var _a, _b, _c;
    return (h("ion-item-divider", { color: "primary", sticky: true, style: {
        display: "flex",
        justifyContent: "space-between",
      } },
      h("div", { class: "location-lookup" },
        h("img", { height: "30", width: "30", class: "map-marker", src: "https://firebasestorage.googleapis.com/v0/b/ftms-ca85b.appspot.com/o/icons%2Fmap-marker.svg?alt=media&token=dda86d6e-b40c-49ce-b60c-928e4de6879d" }),
        !this.changingLocation && (h("h4", { class: "location-city" }, ((_a = this.location) === null || _a === void 0 ? void 0 : _a.name) || "Find a Location")),
        !this.changingLocation && (h("a", { href: "#", onClick: () => (this.changingLocation = true) }, "Change Location")),
        this.changingLocation && [
          h("fireenjin-input", { name: "query", value: this.query, placeholder: "Enter Zip" }),
          h("ion-button", { color: "secondary", onClick: () => this.changeLocation() }, "Set"),
        ]),
      h("ion-button", { class: "location-phone", href: `tel:+${((_b = this.location) === null || _b === void 0 ? void 0 : _b.phone) || "833-424-0044"}`, color: "success", shape: "round", style: { marginLeft: "auto", display: "table" } },
        h("h4", { class: "ion-no-margin ion-no-padding" },
          "Call now: ",
          ((_c = this.location) === null || _c === void 0 ? void 0 : _c.phone) || "833-424-0044"))));
  }
  static get is() { return "floodteam-location-bar"; }
  static get originalStyleUrls() { return {
    "$": ["location-bar.css"]
  }; }
  static get styleUrls() { return {
    "$": ["location-bar.css"]
  }; }
  static get properties() { return {
    "query": {
      "type": "any",
      "mutable": true,
      "complexType": {
        "original": "any",
        "resolved": "any",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "query",
      "reflect": false
    },
    "algoliaAppId": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "algolia-app-id",
      "reflect": false,
      "defaultValue": "\"ZKFP93O6EH\""
    },
    "algoliaSearchKey": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "algolia-search-key",
      "reflect": false,
      "defaultValue": "\"cef2b52143823594c9c5af78ad86bcf0\""
    },
    "algoliaIndex": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "algolia-index",
      "reflect": false,
      "defaultValue": "\"locations\""
    },
    "locationId": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "location-id",
      "reflect": false
    }
  }; }
  static get states() { return {
    "position": {},
    "endOfSearch": {},
    "searchOptions": {},
    "searchResults": {},
    "resultCount": {},
    "searchResultPages": {},
    "changingLocation": {},
    "location": {}
  }; }
  static get methods() { return {
    "findLocation": {
      "complexType": {
        "signature": "(id: string) => Promise<{ objectID?: string; name?: string; path?: string; id?: string; email?: string; phone?: string; type?: string; address?: Address; isSearchable?: boolean; createdAt?: number; updatedAt?: number; _geoloc?: { lat: string; lng: string; }; taxId?: string; lastModified?: number; }>",
        "parameters": [{
            "tags": [],
            "text": ""
          }],
        "references": {
          "Promise": {
            "location": "global"
          },
          "Address": {
            "location": "import",
            "path": "../../../sdk"
          }
        },
        "return": "Promise<{ objectID?: string; name?: string; path?: string; id?: string; email?: string; phone?: string; type?: string; address?: Address; isSearchable?: boolean; createdAt?: number; updatedAt?: number; _geoloc?: { lat: string; lng: string; }; taxId?: string; lastModified?: number; }>"
      },
      "docs": {
        "text": "",
        "tags": []
      }
    },
    "search": {
      "complexType": {
        "signature": "(query: any, options: any) => Promise<any>",
        "parameters": [{
            "tags": [],
            "text": ""
          }, {
            "tags": [],
            "text": ""
          }],
        "references": {
          "Promise": {
            "location": "global"
          }
        },
        "return": "Promise<any>"
      },
      "docs": {
        "text": "",
        "tags": []
      }
    }
  }; }
  static get listeners() { return [{
      "name": "ionInput",
      "method": "onInput",
      "target": undefined,
      "capture": false,
      "passive": false
    }]; }
}
//# sourceMappingURL=location-bar.js.map