import { Build, Event, Component, Listen, h, } from "@stencil/core";
import { modalController, popoverController, toastController, } from "@ionic/core";
import { SocialSharing } from "@ionic-native/social-sharing";
import { AuthService, DatabaseService, FireEnjin, } from "@fireenjin/sdk";
import { initializeApp } from "@firebase/app";
import env from "../helpers/env";
import state from "../store";
import { getSdk, } from "../sdk";
import downloadCSV from "../helpers/downloadCSV";
import pick from "../helpers/pick";
import LogRocket from "logrocket";
import importCsvFile from "../helpers/importCsvFile";
import openFileSelect from "../helpers/openFileSelect";
import uploadFiles from "../helpers/uploadFiles";
import getCache from "../helpers/getCache";
import clearCache from "../helpers/clearCache";
import getParameter from "../helpers/getParameter";
import linkTemplatesToPartials from "../helpers/linkTemplatesToPartials";
export class AppRouter {
  constructor() {
    var _a, _b, _c, _d;
    this.app = (Build === null || Build === void 0 ? void 0 : Build.isBrowser) ? initializeApp(env("firebase", {})) : null;
    this.auth = (Build === null || Build === void 0 ? void 0 : Build.isBrowser)
      ? new AuthService({
        app: this.app,
        config: {
          tokenLocalStorageKey: "floodteam:token",
          authLocalStorageKey: "floodteam:session",
          emulate: !!((_a = state === null || state === void 0 ? void 0 : state.config) === null || _a === void 0 ? void 0 : _a.emulate),
        },
      })
      : null;
    this.db = (Build === null || Build === void 0 ? void 0 : Build.isBrowser)
      ? new DatabaseService({
        app: this.app,
        emulate: !!((_b = state === null || state === void 0 ? void 0 : state.config) === null || _b === void 0 ? void 0 : _b.emulate),
      })
      : null;
    this.fireenjin = Build.isBrowser
      ? new FireEnjin({
        getSdk,
        debug: Build === null || Build === void 0 ? void 0 : Build.isDev,
        connections: [
          {
            name: "default",
            type: "graphql",
            url: (_d = (_c = state === null || state === void 0 ? void 0 : state.config) === null || _c === void 0 ? void 0 : _c.graphql) === null || _d === void 0 ? void 0 : _d.url,
          },
        ],
      })
      : null;
    this.uploadData = {};
  }
  onSuccess(event) {
    var _a, _b;
    if ([
      "addTemplate",
      "editTemplate",
      "listTemplates",
      "deleteTemplate",
    ].includes((_a = event === null || event === void 0 ? void 0 : event.detail) === null || _a === void 0 ? void 0 : _a.endpoint)) {
      this.getTemplates();
    }
    else if (["addPin", "deletePin", "reorderPins"].includes((_b = event === null || event === void 0 ? void 0 : event.detail) === null || _b === void 0 ? void 0 : _b.endpoint)) {
      this.getPins();
    }
  }
  async onToastDidDismiss() {
    this.toast = null;
  }
  async closeToast() {
    this.toast.dismiss();
  }
  async toastMessage(event) {
    var _a;
    if (!this.toast)
      return;
    this.toast.message = (_a = event === null || event === void 0 ? void 0 : event.detail) === null || _a === void 0 ? void 0 : _a.message;
  }
  async openToast(event) {
    this.toast = await toastController.create(event.detail);
    this.toast.present();
  }
  async share(event) {
    try {
      if (navigator === null || navigator === void 0 ? void 0 : navigator.share) {
        await navigator.share(event.detail.data);
        return;
      }
      if (!(navigator === null || navigator === void 0 ? void 0 : navigator.share)) {
        this.sharePopover = await popoverController.create({
          event: event.detail.event,
          component: "fireenjin-share",
          componentProps: {
            options: event.detail.data,
          },
        });
        this.sharePopover.present();
        return;
      }
      await SocialSharing.share(event.detail.data.message, event.detail.data.subject, event.detail.data.file, event.detail.data.url);
    }
    catch (e) {
      console.log("Error using share functionality...", e);
    }
  }
  closeSharePopover() {
    this.sharePopover.dismiss();
  }
  async onForceUpdate() {
    const registrations = await navigator.serviceWorker.getRegistrations();
    await Promise.all(registrations.map((r) => r.unregister()));
    window.location.reload();
  }
  async onSWUpdate() {
    const registration = await navigator.serviceWorker.getRegistration();
    if (!registration || !registration.waiting) {
      // If there is no registration, this is the first service
      // worker to be installed. registration.waiting is the one
      // waiting to be activiated.
      return;
    }
    const toast = await toastController.create({
      message: "New version available",
      buttons: [
        {
          side: "end",
          text: "Reload",
          handler: () => {
            registration.waiting.postMessage("skipWaiting");
            this.onForceUpdate();
          },
        },
      ],
    });
    await toast.present();
  }
  async onTrigger(event) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54;
    const triggerName = ((_a = event === null || event === void 0 ? void 0 : event.detail) === null || _a === void 0 ? void 0 : _a.name) || ((_b = event === null || event === void 0 ? void 0 : event.detail) === null || _b === void 0 ? void 0 : _b.trigger);
    if (triggerName === "pin") {
      this.togglePin((_c = event === null || event === void 0 ? void 0 : event.detail) === null || _c === void 0 ? void 0 : _c.payload);
    }
    else if (triggerName === "setupPayments") {
      this.getStripeAccountUrl();
    }
    else if (triggerName === "export") {
      await downloadCSV({
        data: ((_d = event === null || event === void 0 ? void 0 : event.detail) === null || _d === void 0 ? void 0 : _d.payload) || [],
        filename: ((_e = event === null || event === void 0 ? void 0 : event.detail) === null || _e === void 0 ? void 0 : _e.filename) ||
          `export_${((_f = event === null || event === void 0 ? void 0 : event.detail) === null || _f === void 0 ? void 0 : _f.collection) || "data"}_${new Date().toISOString().split("T")[0]}.csv`,
      });
    }
    else if (triggerName === "import") {
      const files = await openFileSelect();
      importCsvFile(files[0], (_g = event === null || event === void 0 ? void 0 : event.detail) === null || _g === void 0 ? void 0 : _g.type);
    }
    else if (triggerName === "upload") {
      // @TODO Add better error handling and reupload errored ones
      this.uploadQuery = `mutation addEfile($data: EfileInput!) {
            addEfile(data: $data) {
              id
            }
          }`;
      this.fileInputEl.click();
      this.uploadData = {
        tags: ((_j = (_h = event === null || event === void 0 ? void 0 : event.detail) === null || _h === void 0 ? void 0 : _h.payload) === null || _j === void 0 ? void 0 : _j.tags) || [],
        type: ((_l = (_k = event === null || event === void 0 ? void 0 : event.detail) === null || _k === void 0 ? void 0 : _k.payload) === null || _l === void 0 ? void 0 : _l.type) || "upload",
        jobId: ((_o = (_m = event === null || event === void 0 ? void 0 : event.detail) === null || _m === void 0 ? void 0 : _m.payload) === null || _o === void 0 ? void 0 : _o.jobId) || null,
      };
    }
    else if (triggerName === "photos") {
      // @TODO Add better error handling and reupload errored ones
      this.uploadQuery = `mutation addPhoto($data: PhotoInput!) {
            addPhoto(data: $data) {
              id
            }
          }`;
      this.fileInputEl.click();
      this.uploadData = {
        default: !!((_q = (_p = event === null || event === void 0 ? void 0 : event.detail) === null || _p === void 0 ? void 0 : _p.payload) === null || _q === void 0 ? void 0 : _q.default),
        tags: ((_s = (_r = event === null || event === void 0 ? void 0 : event.detail) === null || _r === void 0 ? void 0 : _r.payload) === null || _s === void 0 ? void 0 : _s.tags) || [],
        jobId: ((_u = (_t = event === null || event === void 0 ? void 0 : event.detail) === null || _t === void 0 ? void 0 : _t.payload) === null || _u === void 0 ? void 0 : _u.jobId) || null,
        siteId: ((_w = (_v = event === null || event === void 0 ? void 0 : event.detail) === null || _v === void 0 ? void 0 : _v.payload) === null || _w === void 0 ? void 0 : _w.siteId) || null,
        inventoryId: ((_y = (_x = event === null || event === void 0 ? void 0 : event.detail) === null || _x === void 0 ? void 0 : _x.payload) === null || _y === void 0 ? void 0 : _y.inventoryId) || null,
        serviceId: ((_0 = (_z = event === null || event === void 0 ? void 0 : event.detail) === null || _z === void 0 ? void 0 : _z.payload) === null || _0 === void 0 ? void 0 : _0.serviceId) || null,
      };
    }
    else if (["sort", "filter", "move"].includes(triggerName)) {
      let data = ((_3 = (_2 = (_1 = event === null || event === void 0 ? void 0 : event.detail) === null || _1 === void 0 ? void 0 : _1.payload) === null || _2 === void 0 ? void 0 : _2.control) === null || _3 === void 0 ? void 0 : _3.options)
        ? event.detail.payload.control.options.map((option) => ({
          text: option.label,
          value: option.value,
        }))
        : [];
      if (!(data === null || data === void 0 ? void 0 : data.length) && ((_6 = (_5 = (_4 = event === null || event === void 0 ? void 0 : event.detail) === null || _4 === void 0 ? void 0 : _4.payload) === null || _5 === void 0 ? void 0 : _5.control) === null || _6 === void 0 ? void 0 : _6.endpoint)) {
        const response = await this.fireenjin.sdk[event.detail.payload.control.endpoint]({
          data: ((_9 = (_8 = (_7 = event === null || event === void 0 ? void 0 : event.detail) === null || _7 === void 0 ? void 0 : _7.payload) === null || _8 === void 0 ? void 0 : _8.control) === null || _9 === void 0 ? void 0 : _9.params)
            ? event.detail.payload.control.params
            : {},
        });
        const results = response[((_12 = (_11 = (_10 = event === null || event === void 0 ? void 0 : event.detail) === null || _10 === void 0 ? void 0 : _10.payload) === null || _11 === void 0 ? void 0 : _11.control) === null || _12 === void 0 ? void 0 : _12.resultsKey)
          ? event.detail.payload.control.resultsKey
          : (_15 = (_14 = (_13 = event === null || event === void 0 ? void 0 : event.detail) === null || _13 === void 0 ? void 0 : _13.payload) === null || _14 === void 0 ? void 0 : _14.control) === null || _15 === void 0 ? void 0 : _15.endpoint];
        data = results
          ? results.map((result) => ({
            text: (result === null || result === void 0 ? void 0 : result.name) ? result.name : result.id,
            value: result.id,
          }))
          : [];
      }
      let mobiscroll = window.mobiscroll;
      // if (!mobiscroll) mobiscroll = await import("@mobiscroll/javascript");
      this.floatSelect = mobiscroll.select(this.floatingSelectEl, {
        anchor: event.detail.event.target,
        filter: !!((_17 = (_16 = event === null || event === void 0 ? void 0 : event.detail) === null || _16 === void 0 ? void 0 : _16.payload) === null || _17 === void 0 ? void 0 : _17.filter),
        filterEmptyText: ((_19 = (_18 = event === null || event === void 0 ? void 0 : event.detail) === null || _18 === void 0 ? void 0 : _18.payload) === null || _19 === void 0 ? void 0 : _19.filterEmptyText) || null,
        filterPlaceholderText: ((_21 = (_20 = event === null || event === void 0 ? void 0 : event.detail) === null || _20 === void 0 ? void 0 : _20.payload) === null || _21 === void 0 ? void 0 : _21.filterPlaceholderText) || null,
        buttons: [
          "set",
          {
            text: "Clear",
            handler: () => {
              var _a, _b, _c;
              this.floatSelect.setVal(undefined);
              this.floatSelect.close();
              this.fireenjinTrigger.emit({
                event,
                name: "set",
                payload: {
                  name: (_c = (_b = (_a = event === null || event === void 0 ? void 0 : event.detail) === null || _a === void 0 ? void 0 : _a.payload) === null || _b === void 0 ? void 0 : _b.control) === null || _c === void 0 ? void 0 : _c.name,
                  value: undefined,
                },
              });
            },
          },
        ],
        displayStyle: "anchored",
        display: "anchored",
        onFilter: typeof ((_23 = (_22 = event === null || event === void 0 ? void 0 : event.detail) === null || _22 === void 0 ? void 0 : _22.payload) === null || _23 === void 0 ? void 0 : _23.onFilter) === "function"
          ? event.detail.payload.onFilter.bind(this)
          : null,
        onChange: async (e) => {
          var _a, _b, _c, _d, _e;
          if (triggerName === "move") {
            const photo = await document
              .querySelector("floodteam-photo-carousel")
              .getPhoto();
            this.fireenjinSubmit.emit({
              endpoint: "editPhoto",
              params: {
                id: photo.id,
                data: {
                  siteId: e.value,
                },
              },
            });
          }
          else {
            this.fireenjinTrigger.emit({
              event,
              el: (_a = event === null || event === void 0 ? void 0 : event.detail) === null || _a === void 0 ? void 0 : _a.el,
              name: ((_b = event === null || event === void 0 ? void 0 : event.detail) === null || _b === void 0 ? void 0 : _b.el) ? "select" : "set",
              payload: {
                name: (_e = (_d = (_c = event === null || event === void 0 ? void 0 : event.detail) === null || _c === void 0 ? void 0 : _c.payload) === null || _d === void 0 ? void 0 : _d.control) === null || _e === void 0 ? void 0 : _e.name,
                value: e === null || e === void 0 ? void 0 : e.value,
              },
            });
          }
        },
        selectMultiple: !!((_26 = (_25 = (_24 = event === null || event === void 0 ? void 0 : event.detail) === null || _24 === void 0 ? void 0 : _24.payload) === null || _25 === void 0 ? void 0 : _25.control) === null || _26 === void 0 ? void 0 : _26.multiple),
        data,
      });
      this.floatSelect.setVal((_29 = (_28 = (_27 = event === null || event === void 0 ? void 0 : event.detail) === null || _27 === void 0 ? void 0 : _27.payload) === null || _28 === void 0 ? void 0 : _28.control) === null || _29 === void 0 ? void 0 : _29.value);
      this.floatSelect.open();
    }
    else if (triggerName === "login") {
      const type = ((_31 = (_30 = event === null || event === void 0 ? void 0 : event.detail) === null || _30 === void 0 ? void 0 : _30.payload) === null || _31 === void 0 ? void 0 : _31.type) || "email";
      let res;
      if (type === "email") {
        res = await this.auth.withEmailLink((_33 = (_32 = event === null || event === void 0 ? void 0 : event.detail) === null || _32 === void 0 ? void 0 : _32.payload) === null || _33 === void 0 ? void 0 : _33.email, {
          url: (_34 = state === null || state === void 0 ? void 0 : state.config) === null || _34 === void 0 ? void 0 : _34.url,
          dynamicLinkDomain: (_35 = state === null || state === void 0 ? void 0 : state.config) === null || _35 === void 0 ? void 0 : _35.dynamicLinkDomain,
          iOS: {
            bundleId: "net.madnessenjin.floodteamapp",
          },
          android: {
            packageName: "net.madnessenjin.floodteamapp",
            installApp: false,
            minimumVersion: "12",
          },
          handleCodeInApp: true,
        });
      }
      else if (type === "token") {
        const tempToken = (await this.db.getDocument("tokens", ((_37 = (_36 = event === null || event === void 0 ? void 0 : event.detail) === null || _36 === void 0 ? void 0 : _36.payload) === null || _37 === void 0 ? void 0 : _37.token) || getParameter("token"))).data();
        res = await this.auth.withToken(tempToken.token);
      }
      else {
        res = await this.auth.withSocial(type);
      }
      if ((_38 = res === null || res === void 0 ? void 0 : res.user) === null || _38 === void 0 ? void 0 : _38.uid) {
        const routerEl = document.querySelector("ion-router");
        routerEl.push("dashboard");
      }
    }
    else if (triggerName === "subscribe") {
      this.db.watchDocument((_40 = (_39 = event === null || event === void 0 ? void 0 : event.detail) === null || _39 === void 0 ? void 0 : _39.payload) === null || _40 === void 0 ? void 0 : _40.collection, (_42 = (_41 = event === null || event === void 0 ? void 0 : event.detail) === null || _41 === void 0 ? void 0 : _41.payload) === null || _42 === void 0 ? void 0 : _42.id, typeof ((_44 = (_43 = event === null || event === void 0 ? void 0 : event.detail) === null || _43 === void 0 ? void 0 : _43.payload) === null || _44 === void 0 ? void 0 : _44.callback) === "function"
        ? (_46 = (_45 = event === null || event === void 0 ? void 0 : event.detail) === null || _45 === void 0 ? void 0 : _45.payload) === null || _46 === void 0 ? void 0 : _46.callback
        : ({ data }) => {
          var _a, _b, _c, _d;
          if (!((_b = (_a = event === null || event === void 0 ? void 0 : event.detail) === null || _a === void 0 ? void 0 : _a.payload) === null || _b === void 0 ? void 0 : _b.stateKey))
            return;
          state[(_d = (_c = event === null || event === void 0 ? void 0 : event.detail) === null || _c === void 0 ? void 0 : _c.payload) === null || _d === void 0 ? void 0 : _d.stateKey] = data;
        });
    }
    else if (triggerName === "unsubscribe") {
      this.db.unwatchDocument((_48 = (_47 = event === null || event === void 0 ? void 0 : event.detail) === null || _47 === void 0 ? void 0 : _47.payload) === null || _48 === void 0 ? void 0 : _48.collection, (_50 = (_49 = event === null || event === void 0 ? void 0 : event.detail) === null || _49 === void 0 ? void 0 : _49.payload) === null || _50 === void 0 ? void 0 : _50.id);
    }
    else if (triggerName === "set") {
      if (!(state === null || state === void 0 ? void 0 : state.filters))
        state.filters = {};
      if (!(state === null || state === void 0 ? void 0 : state.filters[location === null || location === void 0 ? void 0 : location.pathname]))
        state.filters[location.pathname] = {};
      state.filters[location.pathname][(_52 = (_51 = event === null || event === void 0 ? void 0 : event.detail) === null || _51 === void 0 ? void 0 : _51.payload) === null || _52 === void 0 ? void 0 : _52.name] =
        (_54 = (_53 = event === null || event === void 0 ? void 0 : event.detail) === null || _53 === void 0 ? void 0 : _53.payload) === null || _54 === void 0 ? void 0 : _54.value;
      state.filters = { ...state.filters };
    }
  }
  closeModal() {
    const modalEls = document.querySelectorAll("ion-modal");
    if (modalEls) {
      modalEls.forEach((modalEl) => modalEl.dismiss());
    }
    this.modal = null;
  }
  async openModal(event) {
    this.modal = await modalController.create(event.detail);
    this.modal.present();
  }
  closePopover() {
    const popoverEls = document.querySelectorAll("ion-popover");
    if (popoverEls) {
      popoverEls.forEach((popoverEl) => popoverEl.dismiss());
    }
  }
  async openPopover(event) {
    this.popover = await popoverController.create(event.detail);
    this.popover.present();
  }
  async logout() {
    await this.auth.logout();
    await this.db.clearWatchers();
    await clearCache();
    window.location.href = "/";
  }
  async onReset(event) {
    var _a;
    if (!((_a = state === null || state === void 0 ? void 0 : state.session) === null || _a === void 0 ? void 0 : _a.uid))
      return;
    if (event.detail.name === "onboarding") {
      const referredById = (await getCache("referredBy"));
      await this.db.update("users", state.session.uid, {
        isOnboarded: true,
        referredBy: referredById
          ? this.db.document("users", referredById)
          : null,
      });
      await clearCache("referredBy");
      await this.modal.dismiss();
    }
  }
  async onRouteDidChange(event) {
    var _a, _b;
    let stopLoader = true;
    if (!Build.isBrowser)
      return false;
    if ((_a = state === null || state === void 0 ? void 0 : state.session) === null || _a === void 0 ? void 0 : _a.id)
      this.fireenjin.setHeader("Authorization", `Bearer ${await this.auth.getToken()}`);
    document.querySelectorAll("[data-trigger]").forEach((triggerEl) => {
      if (triggerEl.getAttribute("triggerer"))
        return;
      triggerEl.addEventListener("click", (triggerEvent) => {
        var _a, _b, _c, _d;
        triggerEvent.preventDefault();
        const name = (_b = (_a = triggerEvent === null || triggerEvent === void 0 ? void 0 : triggerEvent.target) === null || _a === void 0 ? void 0 : _a.dataset) === null || _b === void 0 ? void 0 : _b.trigger;
        const payload = (_d = (_c = triggerEvent === null || triggerEvent === void 0 ? void 0 : triggerEvent.target) === null || _c === void 0 ? void 0 : _c.dataset) === null || _d === void 0 ? void 0 : _d.triggerPayload;
        this.fireenjinTrigger.emit({
          name,
          payload,
        });
      });
      triggerEl.setAttribute("triggerer", "true");
    });
    // if (state?.session?.uid && ["/"].indexOf(event.detail.to) >= 0) {
    //     stopLoader = false;
    //     this.routerEl.push("/dashboard");
    // }
    if (!((_b = state === null || state === void 0 ? void 0 : state.session) === null || _b === void 0 ? void 0 : _b.uid) && ["/dashboard"].indexOf(event.detail.to) >= 0) {
      stopLoader = false;
      if (this.routerEl)
        this.routerEl.push("/");
    }
    if (stopLoader) {
      document.body.classList.add("is-loaded");
    }
  }
  async connectToPlaid() {
    var _a;
    if (!((_a = state === null || state === void 0 ? void 0 : state.session) === null || _a === void 0 ? void 0 : _a.uid))
      return;
    const { createPlaidToken } = await this.fireenjin.sdk.createPlaidToken({
      data: {
        userId: state.session.uid,
      },
    });
    const handler = window.Plaid.create({
      token: createPlaidToken.token,
      onSuccess: async (token) => {
        await this.fireenjin.sdk.setPlaidAccessToken({
          data: {
            userId: state.session.uid,
            token,
          },
        });
      },
      onLoad: () => {
        handler.open();
      },
      onExit: (err, metadata) => {
        console.log(err, metadata);
      },
      onEvent: (eventName, metadata) => {
        console.log(eventName, metadata);
      },
      receivedRedirectUri: null,
    });
  }
  async uploadFiles(event) {
    var _a, _b, _c, _d;
    if (!((_b = (_a = event === null || event === void 0 ? void 0 : event.target) === null || _a === void 0 ? void 0 : _a.files) === null || _b === void 0 ? void 0 : _b.length))
      return;
    this.openToast({
      detail: {
        message: `Uploading files, please wait...`,
      },
    });
    let currentUploadCount = 0;
    const files = await uploadFiles(this.app, event.target.files, {
      path: (_d = (_c = event === null || event === void 0 ? void 0 : event.detail) === null || _c === void 0 ? void 0 : _c.payload) === null || _d === void 0 ? void 0 : _d.path,
      onBeforeUpload: () => {
        currentUploadCount = currentUploadCount + 1;
        this.toastMessage({
          detail: {
            message: `Uploading files ${currentUploadCount} of ${event.target.files.length}...`,
          },
        });
      },
    });
    for (const file of files || []) {
      if (!(file === null || file === void 0 ? void 0 : file.url))
        continue;
      const data = {
        ...this.uploadData,
        url: file === null || file === void 0 ? void 0 : file.url,
      };
      if (this.uploadQuery.includes("addEfile")) {
        data.name = (file === null || file === void 0 ? void 0 : file.name) || new Date().toDateString();
      }
      this.fireenjin.upload({
        query: this.uploadQuery,
        params: {
          data,
        },
      });
    }
    this.closeToast();
  }
  async connectGoogleCalendar() {
    const { generateGoogleAuthUrl } = await this.fireenjin.sdk.generateGoogleAuthUrl({
      data: {},
    });
    window.open(generateGoogleAuthUrl.authUrl, null, "height=650,width=400,status=yes,toolbar=no,menubar=no,location=no");
  }
  async getStripeAccountUrl() {
    var _a, _b, _c;
    if (!((_a = state === null || state === void 0 ? void 0 : state.session) === null || _a === void 0 ? void 0 : _a.uid) || !((_c = (_b = this.fireenjin) === null || _b === void 0 ? void 0 : _b.sdk) === null || _c === void 0 ? void 0 : _c.createStripeAccountLink))
      return;
    const { createStripeAccountLink } = await this.fireenjin.sdk.createStripeAccountLink({
      data: {
        userId: state.session.uid,
      },
    });
    window.location.href = createStripeAccountLink.url;
  }
  async onKeydown(event) {
    if (event.key === "s" &&
      (navigator.platform.match("Mac") ? event.metaKey : event.ctrlKey)) {
      event.preventDefault();
    }
  }
  async togglePin(pin) {
    var _a;
    const currentPin = ((state === null || state === void 0 ? void 0 : state.pins) || []).find((p) => (pin === null || pin === void 0 ? void 0 : pin.id) ? (pin === null || pin === void 0 ? void 0 : pin.id) === (p === null || p === void 0 ? void 0 : p.id) : (pin === null || pin === void 0 ? void 0 : pin.href) === (p === null || p === void 0 ? void 0 : p.href));
    try {
      if (currentPin === null || currentPin === void 0 ? void 0 : currentPin.id) {
        this.fireenjinSubmit.emit({
          endpoint: "deletePin",
          params: {
            id: currentPin.id,
          },
        });
      }
      else {
        this.fireenjinSubmit.emit({
          endpoint: "addPin",
          params: {
            data: { ...pin, userId: (_a = state === null || state === void 0 ? void 0 : state.session) === null || _a === void 0 ? void 0 : _a.uid },
          },
        });
      }
    }
    catch (_b) {
      console.log("Error pinning.");
    }
  }
  async getTemplates() {
    try {
      const templates = await this.db.list("templates", [], "subject", 999);
      state.templates = await linkTemplatesToPartials(templates || []);
    }
    catch (_a) {
      console.log("Error loading templates");
    }
  }
  async getLocations() {
    try {
      const locations = await this.db.list("locations", [], "name", 999);
      state.locations = locations || [];
    }
    catch (e) {
      console.log("Error getting locations", e);
    }
  }
  async getServices() {
    try {
      const services = await this.db.list("services", [], "name", 9999);
      state.services = services || [];
    }
    catch (e) {
      console.log("Error getting services", e);
    }
  }
  async getMyJobs() {
    var _a;
    try {
      const { jobs } = await this.fireenjin.sdk.listJobs({
        data: {
          userId: (_a = state === null || state === void 0 ? void 0 : state.session) === null || _a === void 0 ? void 0 : _a.uid,
          limit: 9999,
        },
        withPayables: true,
      });
      state.myJobs = jobs;
    }
    catch (e) {
      console.log("Error getting my jobs", e);
    }
  }
  async getPins() {
    var _a;
    try {
      const { pins } = await this.fireenjin.sdk.listPins({
        data: {
          userId: (_a = state === null || state === void 0 ? void 0 : state.session) === null || _a === void 0 ? void 0 : _a.uid,
          limit: 9999,
        },
      });
      state.pins = pins;
    }
    catch (e) {
      console.log("Error getting my jobs", e);
    }
  }
  async getManifest() {
    const response = await fetch("/manifest.json");
    const json = await response.json();
    return json;
  }
  componentWillLoad() {
    var _a, _b;
    if (!(Build === null || Build === void 0 ? void 0 : Build.isBrowser))
      return;
    if (!Build.isDev && ((_a = state === null || state === void 0 ? void 0 : state.config) === null || _a === void 0 ? void 0 : _a.logrocketKey)) {
      LogRocket.init((_b = state === null || state === void 0 ? void 0 : state.config) === null || _b === void 0 ? void 0 : _b.logrocketKey);
    }
    this.auth.onAuthChanged(async (session) => {
      var _a, _b;
      try {
        state.manifest = await this.getManifest();
      }
      catch (error) {
        console.log("Error getting manifest.json");
      }
      state.session = session;
      state.claims = (session === null || session === void 0 ? void 0 : session.uid)
        ? pick(await this.auth.getClaims(), [
          "admin",
          "tester",
          "role",
          "locationId",
        ])
        : {};
      if (session && session.uid) {
        if (!Build.isDev && ((_a = state === null || state === void 0 ? void 0 : state.config) === null || _a === void 0 ? void 0 : _a.logrocketKey)) {
          LogRocket.identify(session.uid, {
            name: session.displayName ? session.displayName : null,
            email: (session === null || session === void 0 ? void 0 : session.email) || null,
          });
        }
        this.fireenjin.setHeader("Authorization", `Bearer ${await this.auth.getToken()}`);
        if (Build.isBrowser &&
          ["/", "/login"].includes((_b = window === null || window === void 0 ? void 0 : window.location) === null || _b === void 0 ? void 0 : _b.pathname)) {
          setTimeout(() => {
            const routerEl = document.querySelector("ion-router");
            if (routerEl === null || routerEl === void 0 ? void 0 : routerEl.push)
              routerEl.push("/dashboard");
          }, 200);
        }
        this.getTemplates();
        await this.auth.goOnline();
        if (typeof (session === null || session === void 0 ? void 0 : session.uid) !== "string")
          return;
        this.db.watchDocument("users", session.uid, async (snapshot) => {
          var _a;
          console.log(snapshot);
          if ((_a = snapshot === null || snapshot === void 0 ? void 0 : snapshot.data) === null || _a === void 0 ? void 0 : _a.forceUpdate) {
            await this.db.update("users", session === null || session === void 0 ? void 0 : session.uid, {
              updatedAt: new Date(),
              forceUpdate: false,
            });
            this.onForceUpdate();
          }
          state.profile = (snapshot === null || snapshot === void 0 ? void 0 : snapshot.data) || {
            id: session.uid,
          };
          this.getMyJobs();
          this.getServices();
          this.getLocations();
          this.getPins();
        });
      }
    });
  }
  render() {
    return [
      h("input", { ref: (el) => (this.floatingSelectEl = el), style: { visibility: "hidden", height: "0", width: "0" }, name: "floating" }),
      h("ion-router", { useHash: false },
        h("ion-route", { url: "/", component: "app-login" }),
        h("ion-route", { url: "/home", component: "app-home" }),
        h("ion-route", { url: "/login", component: "app-login" }),
        h("ion-route", { url: "/connect", component: "app-connect" }),
        h("ion-route", { url: "/contracts", component: "app-template-list", componentProps: { contracts: true } }),
        h("ion-route", { url: "/contracts/:templateId", component: "app-template", componentProps: { contracts: true } }),
        h("ion-route", { url: "/pay", component: "app-pay" }),
        h("ion-route", { url: "/pay/:jobId", component: "app-pay" }),
        h("ion-route", { url: "/stripe/:status", component: "app-dashboard" }),
        h("ion-route", { url: "/logs", component: "app-log-list" }),
        h("ion-route", { url: "/payments", component: "app-payment-list" }),
        h("ion-route", { url: "/payments/locations/:locationId", component: "app-payment-list" }),
        h("ion-route", { url: "/pins", component: "app-pin-list" }),
        h("ion-route", { url: "/atmospherics", component: "app-atmospheric-list" }),
        h("ion-route", { url: "/exhausts", component: "app-exhaust-list" }),
        h("ion-route", { url: "/dots", component: "app-dot-list" }),
        h("ion-route", { url: "/moisturecontents", component: "app-moisture-content-list" }),
        h("ion-route", { url: "/phonenumbers", component: "app-phone-number-list" }),
        h("ion-route", { url: "/campaigns", component: "app-campaign-list" }),
        h("ion-route", { url: "/campaigns/:campaignId", component: "app-campaign" }),
        h("ion-route", { url: "/paymodels", component: "app-paymodel-list" }),
        h("ion-route", { url: "/paymodels/:paymodelId", component: "app-paymodel" }),
        h("ion-route", { url: "/templates", component: "app-template-list" }),
        h("ion-route", { component: "app-template", url: "/templates/:templateId" }),
        h("ion-route", { url: "/totallers", component: "app-totaller-list" }),
        h("ion-route", { url: "/totallers/:totallerId", component: "app-totaller" }),
        h("ion-route", { url: "/alerts", component: "app-alert-list" }),
        h("ion-route", { url: "/import", component: "app-import" }),
        h("ion-route", { url: "/triggers/:triggerId", component: "app-trigger" }),
        h("ion-route", { url: "/triggers", component: "app-trigger-list" }),
        h("ion-route", { url: "/alerts/:alertId", component: "app-alert" }),
        h("ion-route", { url: "/services", component: "app-service-list" }),
        h("ion-route", { url: "/services/:serviceId", component: "app-service" }),
        h("ion-route", { url: "/equipment", component: "app-equipment-list" }),
        h("ion-route", { url: "/equipment/:equipmentId", component: "app-equipment" }),
        h("ion-route", { url: "/inventory", component: "app-inventory-list" }),
        h("ion-route", { url: "/inventory/:itemId", component: "app-inventory" }),
        h("ion-route", { url: "/locations", component: "app-location-list" }),
        h("ion-route", { url: "/locations/:locationId", component: "app-location" }),
        h("ion-route", { url: "/appointments", component: "app-appointment-list" }),
        h("ion-route", { url: "/appointments/:appointmentId", component: "app-appointment" }),
        h("ion-route", { url: "/vehicles", component: "app-vehicle-list" }),
        h("ion-route", { url: "/vehicles/:vehicleId", component: "app-vehicle" }),
        h("ion-route", { url: "/companies", component: "app-company-list" }),
        h("ion-route", { url: "/companies/:companyId", component: "app-company" }),
        h("ion-route", { url: "/weather", component: "app-weather-list" }),
        h("ion-route", { url: "/dashboard", component: "app-dashboard" }),
        h("ion-route", { url: "/jobs", component: "app-job-list" }),
        h("ion-route", { url: "/jobs/:jobId", component: "app-job" }),
        h("ion-route", { url: "/jobs/:jobId/scope", component: "app-scope" }),
        h("ion-route", { url: "/jobs/:jobId/sign/:templateId", component: "app-sign" }),
        h("ion-route", { url: "/jobs/:jobId/site/:siteId", component: "app-job" }),
        h("ion-route", { url: "/jobs/book", component: "app-job-new", componentProps: { referring: true } }),
        h("ion-route", { url: "/jobs/new", component: "app-job-new" }),
        h("ion-route", { url: "/jobs/refer", component: "app-job-new", componentProps: { referring: true } }),
        h("ion-route", { url: "/jobs/refer/:locationId", component: "app-job-new", componentProps: { referring: true } }),
        h("ion-route", { url: "/users", component: "app-user-list" }),
        h("ion-route", { url: "/users/:userId", component: "app-user" }),
        h("ion-route", { url: "/users/:userId/jobs", component: "app-job-list" })),
      h("input", { ref: (el) => (this.fileInputEl = el), type: "file", multiple: true, onChange: (event) => this.uploadFiles(event), name: "uploader", style: { height: "0px", width: "0px", opacity: "0" } }),
    ];
  }
  static get is() { return "floodteam-router"; }
  static get events() { return [{
      "method": "fireenjinSubmit",
      "name": "fireenjinSubmit",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "FireEnjinSubmitEvent",
        "resolved": "FireEnjinSubmitEvent",
        "references": {
          "FireEnjinSubmitEvent": {
            "location": "import",
            "path": "@fireenjin/sdk"
          }
        }
      }
    }, {
      "method": "fireenjinTrigger",
      "name": "fireenjinTrigger",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "FireEnjinTriggerInput",
        "resolved": "FireEnjinTriggerInput",
        "references": {
          "FireEnjinTriggerInput": {
            "location": "import",
            "path": "@fireenjin/sdk"
          }
        }
      }
    }, {
      "method": "fireenjinUpload",
      "name": "fireenjinUpload",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "FireEnjinUploadEvent",
        "resolved": "FireEnjinUploadEvent",
        "references": {
          "FireEnjinUploadEvent": {
            "location": "import",
            "path": "@fireenjin/sdk"
          }
        }
      }
    }]; }
  static get listeners() { return [{
      "name": "fireenjinSuccess",
      "method": "onSuccess",
      "target": "document",
      "capture": false,
      "passive": false
    }, {
      "name": "ionToastDidDismiss",
      "method": "onToastDidDismiss",
      "target": "document",
      "capture": false,
      "passive": false
    }, {
      "name": "floodteamCloseToast",
      "method": "closeToast",
      "target": "document",
      "capture": false,
      "passive": false
    }, {
      "name": "floodteamToastMessage",
      "method": "toastMessage",
      "target": "document",
      "capture": false,
      "passive": false
    }, {
      "name": "floodteamOpenToast",
      "method": "openToast",
      "target": "document",
      "capture": false,
      "passive": false
    }, {
      "name": "floodteamShare",
      "method": "share",
      "target": "document",
      "capture": false,
      "passive": false
    }, {
      "name": "floodteamShareClose",
      "method": "closeSharePopover",
      "target": "document",
      "capture": false,
      "passive": false
    }, {
      "name": "forceUpdate",
      "method": "onForceUpdate",
      "target": "window",
      "capture": false,
      "passive": false
    }, {
      "name": "swUpdate",
      "method": "onSWUpdate",
      "target": "window",
      "capture": false,
      "passive": false
    }, {
      "name": "fireenjinTrigger",
      "method": "onTrigger",
      "target": "document",
      "capture": false,
      "passive": false
    }, {
      "name": "floodteamCloseModal",
      "method": "closeModal",
      "target": "body",
      "capture": false,
      "passive": false
    }, {
      "name": "floodteamOpenModal",
      "method": "openModal",
      "target": "body",
      "capture": false,
      "passive": false
    }, {
      "name": "floodteamClosePopover",
      "method": "closePopover",
      "target": "body",
      "capture": false,
      "passive": false
    }, {
      "name": "floodteamOpenPopover",
      "method": "openPopover",
      "target": "body",
      "capture": false,
      "passive": false
    }, {
      "name": "floodteamLogout",
      "method": "logout",
      "target": "body",
      "capture": false,
      "passive": false
    }, {
      "name": "fireenjinReset",
      "method": "onReset",
      "target": "body",
      "capture": false,
      "passive": false
    }, {
      "name": "ionRouteDidChange",
      "method": "onRouteDidChange",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "keydown",
      "method": "onKeydown",
      "target": "document",
      "capture": false,
      "passive": false
    }]; }
}
//# sourceMappingURL=router.js.map