import { Build, h, } from "@stencil/core";
import { modalController, popoverController, toastController, } from "@ionic/core";
import { SocialSharing } from "@ionic-native/social-sharing";
import { AuthService, DatabaseService, } from "@fireenjin/sdk";
import { initializeApp } from "@firebase/app";
import env from "../helpers/env";
import state from "../store";
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";
import findJob from "../contracts/job/findJob";
import findUser from "../contracts/user/findUser";
import listJobs from "../contracts/job/listJobs";
import editJob from "../contracts/job/editJob";
import addJob from "../contracts/job/addJob";
import listSites from "../contracts/site/listSites";
import findSite from "../contracts/site/findSite";
import listUsers from "../contracts/user/listUsers";
import addSite from "../contracts/site/addSite";
import editSite from "../contracts/site/editSite";
import listServices from "../contracts/service/listServices";
import listPins from "../contracts/pin/listPins";
import findLocation from "../contracts/location/findLocation";
import listLocations from "../contracts/location/listLocations";
import findTrigger from "../contracts/trigger/findTrigger";
import listTriggers from "../contracts/trigger/listTriggers";
import addScopeService from "../contracts/service/addScopeService";
import findTotaller from "../contracts/totaller/findTotaller";
import listTotallers from "../contracts/totaller/listTotallers";
import editScopeService from "../contracts/service/editScopeService";
import deleteScopeService from "../contracts/service/deleteScopeService";
import addUserToJob from "../contracts/job/addUserToJob";
import removeUserFromJob from "../contracts/job/removeUserFromJob";
import editTotaller from "../contracts/totaller/editTotaller";
import addTotaller from "../contracts/totaller/addTotaller";
import addUser from "../contracts/user/addUser";
import editUser from "../contracts/user/editUser";
import addPayment from "../contracts/payment/addPayment";
import listPayment from "../contracts/payment/listPayment";
import generatePdf from "../contracts/efile/generatePdf";
import addEfile from "../contracts/efile/addEfile";
import addPhoto from "../contracts/photo/addPhoto";
import addLocation from "../contracts/location/addLocation";
import editLocation from "../contracts/location/editLocation";
import signContract from "../contracts/efile/signContract";
import sendTemplateEmail from "../contracts/template/sendTemplateEmail";
import deleteSite from "../contracts/site/deleteSite";
import addPin from "../contracts/pin/addPin";
import listWeather from "../contracts/weather/listWeather";
import listExhausts from "../contracts/exhaust readings/listExhausts";
import listVehicles from "../contracts/vehicles/listVehicles";
import listPhoneNumbers from "../contracts/phone numbers/listPhoneNumbers";
import deleteEfile from "../contracts/efile/deleteEfile";
import deletePin from "../contracts/pin/deletePin";
import editTemplate from "../contracts/template/editTemplate";
import findTemplate from "../contracts/template/findTemplate";
import addTemplate from "../contracts/template/addTemplate";
import updateJobAmounts from "../helpers/updateJobAmounts";
import findTotals from "../contracts/totals/findTotals";
import calculateTotaller from "../contracts/totaller/calculateTotaller";
import createStripeOAuthToken from "../contracts/user/createStripeOauthToken";
import createStripeAccountLink from "../contracts/user/createStripeAccountLink";
import addPaymentMethod from "../contracts/user/addPaymentMethod";
import removePaymentMethod from "../contracts/user/removePaymentMethod";
import addNote from "../contracts/note/addNote";
import deleteNote from "../contracts/note/deleteNote";
import listFeeds from "../contracts/feed/listFeed";
import listTotals from "../contracts/totals/listTotals";
import searchUsers from "../contracts/user/searchUsers";
import searchJobs from "../contracts/job/searchJobs";
import editTrigger from "../contracts/trigger/editTrigger";
import addTrigger from "../contracts/trigger/addTrigger";
import listAlerts from "../contracts/alert/listAlerts";
import addAlert from "../contracts/alert/addAlert";
import deletePhoto from "../contracts/photo/deletePhoto";
import editPhoto from "../contracts/photo/editPhoto";
import addCompany from "../contracts/company/addCompany";
import editCompany from "../contracts/company/editCompany";
import findCompany from "../contracts/company/findCompany";
import listCompanies from "../contracts/company/listCompanies";
export class AppRouter {
  constructor() {
    var _a, _b;
    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.uploadData = {};
  }
  async onFetch(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, _55;
    let data = null;
    const endpoint = (_a = event === null || event === void 0 ? void 0 : event.detail) === null || _a === void 0 ? void 0 : _a.endpoint;
    console.log(event.detail);
    if (endpoint === "findJob") {
      const job = await findJob(this.db, (_b = event === null || event === void 0 ? void 0 : event.detail) === null || _b === void 0 ? void 0 : _b.params);
      data = {
        job,
      };
      if ((_c = event === null || event === void 0 ? void 0 : event.detail) === null || _c === void 0 ? void 0 : _c.cacheKey)
        state.jobs = {
          ...((state === null || state === void 0 ? void 0 : state.jobs) || {}),
          [(_d = data === null || data === void 0 ? void 0 : data.job) === null || _d === void 0 ? void 0 : _d.id]: job,
        };
    }
    else if (endpoint === "listJobs") {
      data = {
        jobs: ((_h = (_g = (_f = (_e = event === null || event === void 0 ? void 0 : event.detail) === null || _e === void 0 ? void 0 : _e.params) === null || _f === void 0 ? void 0 : _f.data) === null || _g === void 0 ? void 0 : _g.query) === null || _h === void 0 ? void 0 : _h.length)
          ? await searchJobs((_k = (_j = event === null || event === void 0 ? void 0 : event.detail) === null || _j === void 0 ? void 0 : _j.params) === null || _k === void 0 ? void 0 : _k.data, {
            algoliaId: (_m = (_l = state === null || state === void 0 ? void 0 : state.config) === null || _l === void 0 ? void 0 : _l.algolia) === null || _m === void 0 ? void 0 : _m.appId,
            algoliaKey: (_p = (_o = state === null || state === void 0 ? void 0 : state.config) === null || _o === void 0 ? void 0 : _o.algolia) === null || _p === void 0 ? void 0 : _p.searchKey,
          })
          : await listJobs(this.db, (_q = event === null || event === void 0 ? void 0 : event.detail) === null || _q === void 0 ? void 0 : _q.params),
      };
    }
    else if (endpoint === "findTotaller") {
      data = {
        totaller: await findTotaller(this.db, ((_r = event === null || event === void 0 ? void 0 : event.detail) === null || _r === void 0 ? void 0 : _r.id) || ((_t = (_s = event === null || event === void 0 ? void 0 : event.detail) === null || _s === void 0 ? void 0 : _s.params) === null || _t === void 0 ? void 0 : _t.id)),
      };
    }
    else if (endpoint === "listTotallers") {
      data = {
        totallers: await listTotallers(this.db, (_u = event === null || event === void 0 ? void 0 : event.detail) === null || _u === void 0 ? void 0 : _u.params),
      };
    }
    else if (endpoint === "listAlerts") {
      data = {
        alerts: await listAlerts(this.db, (_v = event === null || event === void 0 ? void 0 : event.detail) === null || _v === void 0 ? void 0 : _v.params),
      };
    }
    else if (endpoint === "findLocation") {
      data = {
        location: await findLocation(this.db, ((_w = event === null || event === void 0 ? void 0 : event.detail) === null || _w === void 0 ? void 0 : _w.id) || ((_y = (_x = event === null || event === void 0 ? void 0 : event.detail) === null || _x === void 0 ? void 0 : _x.params) === null || _y === void 0 ? void 0 : _y.id)),
      };
    }
    else if (endpoint === "findTemplate") {
      data = {
        template: await findTemplate(this.db, ((_z = event === null || event === void 0 ? void 0 : event.detail) === null || _z === void 0 ? void 0 : _z.id) || ((_1 = (_0 = event === null || event === void 0 ? void 0 : event.detail) === null || _0 === void 0 ? void 0 : _0.params) === null || _1 === void 0 ? void 0 : _1.id)),
      };
    }
    else if (endpoint === "listLocations") {
      data = {
        locations: await listLocations(this.db, (_2 = event === null || event === void 0 ? void 0 : event.detail) === null || _2 === void 0 ? void 0 : _2.params),
      };
    }
    else if (endpoint === "listPayments") {
      data = {
        payments: await listPayment(this.db, (_3 = event === null || event === void 0 ? void 0 : event.detail) === null || _3 === void 0 ? void 0 : _3.params),
      };
    }
    else if (endpoint === "findCompany") {
      data = {
        company: await findCompany(this.db, ((_4 = event === null || event === void 0 ? void 0 : event.detail) === null || _4 === void 0 ? void 0 : _4.id) || ((_6 = (_5 = event === null || event === void 0 ? void 0 : event.detail) === null || _5 === void 0 ? void 0 : _5.params) === null || _6 === void 0 ? void 0 : _6.id)),
      };
    }
    else if (endpoint === "listCompanies") {
      data = {
        companies: await listCompanies(this.db, (_7 = event === null || event === void 0 ? void 0 : event.detail) === null || _7 === void 0 ? void 0 : _7.params),
      };
    }
    else if (endpoint === "findUser") {
      data = {
        user: await findUser(this.db, ((_8 = event === null || event === void 0 ? void 0 : event.detail) === null || _8 === void 0 ? void 0 : _8.id) || ((_10 = (_9 = event === null || event === void 0 ? void 0 : event.detail) === null || _9 === void 0 ? void 0 : _9.params) === null || _10 === void 0 ? void 0 : _10.id)),
      };
    }
    else if (endpoint === "listUsers") {
      data = {
        users: ((_14 = (_13 = (_12 = (_11 = event === null || event === void 0 ? void 0 : event.detail) === null || _11 === void 0 ? void 0 : _11.params) === null || _12 === void 0 ? void 0 : _12.data) === null || _13 === void 0 ? void 0 : _13.query) === null || _14 === void 0 ? void 0 : _14.length)
          ? await searchUsers((_16 = (_15 = event === null || event === void 0 ? void 0 : event.detail) === null || _15 === void 0 ? void 0 : _15.params) === null || _16 === void 0 ? void 0 : _16.data, {
            algoliaId: (_18 = (_17 = state === null || state === void 0 ? void 0 : state.config) === null || _17 === void 0 ? void 0 : _17.algolia) === null || _18 === void 0 ? void 0 : _18.appId,
            algoliaKey: (_20 = (_19 = state === null || state === void 0 ? void 0 : state.config) === null || _19 === void 0 ? void 0 : _19.algolia) === null || _20 === void 0 ? void 0 : _20.searchKey,
          })
          : await listUsers(this.db, (_21 = event === null || event === void 0 ? void 0 : event.detail) === null || _21 === void 0 ? void 0 : _21.params),
      };
    }
    else if (endpoint === "listSites") {
      data = {
        sites: await listSites(this.db, (_22 = event === null || event === void 0 ? void 0 : event.detail) === null || _22 === void 0 ? void 0 : _22.params),
      };
    }
    else if (endpoint === "findSite") {
      data = {
        site: await findSite(this.db, ((_23 = event === null || event === void 0 ? void 0 : event.detail) === null || _23 === void 0 ? void 0 : _23.id) || ((_25 = (_24 = event === null || event === void 0 ? void 0 : event.detail) === null || _24 === void 0 ? void 0 : _24.params) === null || _25 === void 0 ? void 0 : _25.id)),
      };
    }
    else if (endpoint === "listTriggers") {
      data = {
        triggers: await listTriggers(this.db, (_26 = event === null || event === void 0 ? void 0 : event.detail) === null || _26 === void 0 ? void 0 : _26.params),
      };
    }
    else if (endpoint === "findTrigger") {
      data = {
        trigger: await findTrigger(this.db, ((_27 = event === null || event === void 0 ? void 0 : event.detail) === null || _27 === void 0 ? void 0 : _27.id) || ((_29 = (_28 = event === null || event === void 0 ? void 0 : event.detail) === null || _28 === void 0 ? void 0 : _28.params) === null || _29 === void 0 ? void 0 : _29.id)),
      };
    }
    else if (endpoint === "findTotals") {
      data = {
        totals: await findTotals(this.db, (_31 = (_30 = event === null || event === void 0 ? void 0 : event.detail) === null || _30 === void 0 ? void 0 : _30.params) === null || _31 === void 0 ? void 0 : _31.path),
      };
    }
    else if (endpoint === "listTotals") {
      data = {
        totals: await listTotals(this.db, (_33 = (_32 = event === null || event === void 0 ? void 0 : event.detail) === null || _32 === void 0 ? void 0 : _32.params) === null || _33 === void 0 ? void 0 : _33.path),
      };
    }
    else if (endpoint === "listWeather") {
      data = {
        weather: await listWeather(this.db, (_34 = event === null || event === void 0 ? void 0 : event.detail) === null || _34 === void 0 ? void 0 : _34.params),
      };
    }
    else if (endpoint === "listExhausts") {
      data = {
        exhausts: await listExhausts(this.db, (_35 = event === null || event === void 0 ? void 0 : event.detail) === null || _35 === void 0 ? void 0 : _35.params),
      };
    }
    else if (endpoint === "listVehicles") {
      data = {
        vehicles: await listVehicles(this.db, (_36 = event === null || event === void 0 ? void 0 : event.detail) === null || _36 === void 0 ? void 0 : _36.params),
      };
    }
    else if (endpoint === "listPhoneNumbers") {
      data = {
        phoneNumbers: await listPhoneNumbers(this.db, (_37 = event === null || event === void 0 ? void 0 : event.detail) === null || _37 === void 0 ? void 0 : _37.params),
      };
    }
    else if (endpoint === "listPaymentMethods") {
      data = {
        paymentMethods: await this.getPaymentMethods(),
      };
    }
    else if (endpoint === "listFeeds") {
      console.log(event.detail);
      data = {
        feeds: await listFeeds(this.db, (_39 = (_38 = event === null || event === void 0 ? void 0 : event.detail) === null || _38 === void 0 ? void 0 : _38.params) === null || _39 === void 0 ? void 0 : _39.data),
      };
    }
    else if (endpoint === "searchUsers") {
      data = {
        users: await searchUsers((_40 = event === null || event === void 0 ? void 0 : event.detail) === null || _40 === void 0 ? void 0 : _40.params, {
          algoliaId: (_42 = (_41 = state === null || state === void 0 ? void 0 : state.config) === null || _41 === void 0 ? void 0 : _41.algolia) === null || _42 === void 0 ? void 0 : _42.appId,
          algoliaKey: (_44 = (_43 = state === null || state === void 0 ? void 0 : state.config) === null || _43 === void 0 ? void 0 : _43.algolia) === null || _44 === void 0 ? void 0 : _44.searchKey,
        }),
      };
    }
    else if (endpoint === "searchJobs") {
      data = {
        jobs: await searchJobs((_45 = event === null || event === void 0 ? void 0 : event.detail) === null || _45 === void 0 ? void 0 : _45.params, {
          algoliaId: (_47 = (_46 = state === null || state === void 0 ? void 0 : state.config) === null || _46 === void 0 ? void 0 : _46.algolia) === null || _47 === void 0 ? void 0 : _47.appId,
          algoliaKey: (_49 = (_48 = state === null || state === void 0 ? void 0 : state.config) === null || _48 === void 0 ? void 0 : _48.algolia) === null || _49 === void 0 ? void 0 : _49.searchKey,
        }),
      };
    }
    console.log(event.detail.endpoint, data);
    // console.dir(event.target);
    event.target.dispatchEvent(new CustomEvent(data ? "fireenjinSuccess" : "fireenjinError", {
      bubbles: true,
      cancelable: true,
      detail: {
        event,
        bubbles: (_51 = (_50 = event === null || event === void 0 ? void 0 : event.detail) === null || _50 === void 0 ? void 0 : _50.bubbles) !== null && _51 !== void 0 ? _51 : true,
        cancelable: (_53 = (_52 = event === null || event === void 0 ? void 0 : event.detail) === null || _52 === void 0 ? void 0 : _52.cancelable) !== null && _53 !== void 0 ? _53 : true,
        data,
        endpoint: (_54 = event === null || event === void 0 ? void 0 : event.detail) === null || _54 === void 0 ? void 0 : _54.endpoint,
        method: "get",
        name: (_55 = event === null || event === void 0 ? void 0 : event.detail) === null || _55 === void 0 ? void 0 : _55.name,
        target: event.target,
      },
    }));
  }
  async onSubmit(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, _55, _56;
    let data = null;
    const endpoint = (_a = event === null || event === void 0 ? void 0 : event.detail) === null || _a === void 0 ? void 0 : _a.endpoint;
    const detail = {
      event,
      data: null,
      error: null,
      bubbles: (_c = (_b = event === null || event === void 0 ? void 0 : event.detail) === null || _b === void 0 ? void 0 : _b.bubbles) !== null && _c !== void 0 ? _c : true,
      cancelable: (_e = (_d = event === null || event === void 0 ? void 0 : event.detail) === null || _d === void 0 ? void 0 : _d.cancelable) !== null && _e !== void 0 ? _e : true,
      endpoint: (_f = event === null || event === void 0 ? void 0 : event.detail) === null || _f === void 0 ? void 0 : _f.endpoint,
      method: "post",
      name: (_g = event === null || event === void 0 ? void 0 : event.detail) === null || _g === void 0 ? void 0 : _g.name,
      target: event.target,
    };
    console.log(event.detail);
    try {
      if (endpoint === "addJob") {
        data = {
          addJob: await addJob(this.db, (_h = event === null || event === void 0 ? void 0 : event.detail) === null || _h === void 0 ? void 0 : _h.data),
        };
      }
      else if (endpoint === "editJob") {
        data = {
          editJob: await editJob(this.db, ((_j = event.detail) === null || _j === void 0 ? void 0 : _j.id) || ((_l = (_k = event === null || event === void 0 ? void 0 : event.detail) === null || _k === void 0 ? void 0 : _k.params) === null || _l === void 0 ? void 0 : _l.id), (_m = event === null || event === void 0 ? void 0 : event.detail) === null || _m === void 0 ? void 0 : _m.data),
        };
      }
      else if (endpoint === "addLocation") {
        data = {
          addLocation: await addLocation(this.db, (_o = event === null || event === void 0 ? void 0 : event.detail) === null || _o === void 0 ? void 0 : _o.data),
        };
      }
      else if (endpoint === "editLocation") {
        data = {
          editLocation: await editLocation(this.db, ((_p = event.detail) === null || _p === void 0 ? void 0 : _p.id) || ((_r = (_q = event === null || event === void 0 ? void 0 : event.detail) === null || _q === void 0 ? void 0 : _q.params) === null || _r === void 0 ? void 0 : _r.id), (_s = event === null || event === void 0 ? void 0 : event.detail) === null || _s === void 0 ? void 0 : _s.data),
        };
      }
      else if (endpoint === "editTrigger") {
        data = {
          editTrigger: await editTrigger(this.db, ((_t = event.detail) === null || _t === void 0 ? void 0 : _t.id) || ((_v = (_u = event === null || event === void 0 ? void 0 : event.detail) === null || _u === void 0 ? void 0 : _u.params) === null || _v === void 0 ? void 0 : _v.id), (_w = event === null || event === void 0 ? void 0 : event.detail) === null || _w === void 0 ? void 0 : _w.data),
        };
      }
      else if (endpoint === "addAlert") {
        data = {
          addAlert: await addAlert(this.db, (_x = event === null || event === void 0 ? void 0 : event.detail) === null || _x === void 0 ? void 0 : _x.data),
        };
      }
      else if (endpoint === "addTrigger") {
        data = {
          addTrigger: await addTrigger(this.db, (_y = event === null || event === void 0 ? void 0 : event.detail) === null || _y === void 0 ? void 0 : _y.data),
        };
      }
      else if (endpoint === "editTotaller") {
        data = {
          editTotaller: await editTotaller(this.db, ((_z = event.detail) === null || _z === void 0 ? void 0 : _z.id) || ((_1 = (_0 = event === null || event === void 0 ? void 0 : event.detail) === null || _0 === void 0 ? void 0 : _0.params) === null || _1 === void 0 ? void 0 : _1.id), (_2 = event === null || event === void 0 ? void 0 : event.detail) === null || _2 === void 0 ? void 0 : _2.data),
        };
      }
      else if (endpoint === "addTotaller") {
        data = {
          addTotaller: await addTotaller(this.db, (_3 = event === null || event === void 0 ? void 0 : event.detail) === null || _3 === void 0 ? void 0 : _3.data),
        };
      }
      else if (endpoint === "addPayment") {
        data = {
          addPayment: await addPayment(this.db, (_4 = event === null || event === void 0 ? void 0 : event.detail) === null || _4 === void 0 ? void 0 : _4.data),
        };
      }
      else if (endpoint === "addSite") {
        data = {
          addSite: await addSite(this.db, (_5 = event === null || event === void 0 ? void 0 : event.detail) === null || _5 === void 0 ? void 0 : _5.data),
        };
      }
      else if (endpoint === "editSite") {
        data = {
          editSite: await editSite(this.db, ((_6 = event.detail) === null || _6 === void 0 ? void 0 : _6.id) || ((_8 = (_7 = event === null || event === void 0 ? void 0 : event.detail) === null || _7 === void 0 ? void 0 : _7.params) === null || _8 === void 0 ? void 0 : _8.id), (_9 = event === null || event === void 0 ? void 0 : event.detail) === null || _9 === void 0 ? void 0 : _9.data),
        };
      }
      else if (endpoint === "addPin") {
        data = {
          addPin: await addPin(this.db, (_10 = event === null || event === void 0 ? void 0 : event.detail) === null || _10 === void 0 ? void 0 : _10.data),
        };
      }
      else if (endpoint === "addScopeService") {
        data = {
          addScopeService: await addScopeService(this.db, (_11 = event === null || event === void 0 ? void 0 : event.detail) === null || _11 === void 0 ? void 0 : _11.data),
        };
      }
      else if (endpoint === "editScopeService") {
        data = {
          editScopeService: await editScopeService(this.db, (_12 = event.detail) === null || _12 === void 0 ? void 0 : _12.data),
        };
      }
      else if (endpoint === "deleteScopeService") {
        data = {
          deleteScopeService: await deleteScopeService(this.db, (_13 = event.detail) === null || _13 === void 0 ? void 0 : _13.data),
        };
      }
      else if (endpoint === "addUserToJob") {
        data = {
          addUserToJob: await addUserToJob(this.db, (_14 = event.detail) === null || _14 === void 0 ? void 0 : _14.data),
        };
      }
      else if (endpoint === "removeUserFromJob") {
        data = {
          removeUserFromJob: await removeUserFromJob(this.db, (_15 = event.detail) === null || _15 === void 0 ? void 0 : _15.data),
        };
      }
      else if (endpoint === "addUser") {
        data = {
          addUser: await addUser(this.db, (_16 = event === null || event === void 0 ? void 0 : event.detail) === null || _16 === void 0 ? void 0 : _16.data),
        };
      }
      else if (endpoint === "editUser") {
        data = {
          editUser: await editUser(this.db, ((_17 = event.detail) === null || _17 === void 0 ? void 0 : _17.id) || ((_19 = (_18 = event === null || event === void 0 ? void 0 : event.detail) === null || _18 === void 0 ? void 0 : _18.params) === null || _19 === void 0 ? void 0 : _19.id), (_20 = event === null || event === void 0 ? void 0 : event.detail) === null || _20 === void 0 ? void 0 : _20.data),
        };
      }
      else if (endpoint === "generatePdf") {
        data = {
          generatePdf: await generatePdf(this.db, ((_22 = (_21 = event === null || event === void 0 ? void 0 : event.detail) === null || _21 === void 0 ? void 0 : _21.params) === null || _22 === void 0 ? void 0 : _22.data) || ((_23 = event === null || event === void 0 ? void 0 : event.detail) === null || _23 === void 0 ? void 0 : _23.data)),
        };
      }
      else if (endpoint === "signContract") {
        data = {
          signContract: await signContract(this.db, (_24 = event === null || event === void 0 ? void 0 : event.detail) === null || _24 === void 0 ? void 0 : _24.data),
        };
      }
      else if (endpoint === "sendTemplateEmail") {
        data = {
          sendTemplateEmail: await sendTemplateEmail(this.db, (_25 = event === null || event === void 0 ? void 0 : event.detail) === null || _25 === void 0 ? void 0 : _25.data),
        };
      }
      else if (endpoint === "deleteSite") {
        data = {
          deleteSite: await deleteSite(this.db, (_27 = (_26 = event === null || event === void 0 ? void 0 : event.detail) === null || _26 === void 0 ? void 0 : _26.data) === null || _27 === void 0 ? void 0 : _27.id),
        };
        if ((_28 = state === null || state === void 0 ? void 0 : state.job) === null || _28 === void 0 ? void 0 : _28.sites) {
          state.job.sites = (((_29 = state === null || state === void 0 ? void 0 : state.job) === null || _29 === void 0 ? void 0 : _29.sites) || []).filter((site) => { var _a, _b; return (site === null || site === void 0 ? void 0 : site.id) !== ((_b = (_a = event === null || event === void 0 ? void 0 : event.detail) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.id); });
          state.job = { ...state.job };
        }
      }
      else if (endpoint === "deleteEfile") {
        data = {
          deleteEfile: await deleteEfile(this.db, (_30 = event === null || event === void 0 ? void 0 : event.detail) === null || _30 === void 0 ? void 0 : _30.id),
        };
      }
      else if (endpoint === "editPhoto") {
        data = {
          deletePhoto: await editPhoto(this.db, (_31 = event === null || event === void 0 ? void 0 : event.detail) === null || _31 === void 0 ? void 0 : _31.id, (_32 = event === null || event === void 0 ? void 0 : event.detail) === null || _32 === void 0 ? void 0 : _32.data),
        };
      }
      else if (endpoint === "deletePhoto") {
        data = {
          deletePhoto: await deletePhoto(this.db, (_33 = event === null || event === void 0 ? void 0 : event.detail) === null || _33 === void 0 ? void 0 : _33.id),
        };
      }
      else if (endpoint === "deletePin") {
        data = {
          deletePin: await deletePin(this.db, (_34 = event === null || event === void 0 ? void 0 : event.detail) === null || _34 === void 0 ? void 0 : _34.id),
        };
      }
      else if (endpoint === "editTemplate") {
        data = {
          editTemplate: await editTemplate(this.db, (_35 = event === null || event === void 0 ? void 0 : event.detail) === null || _35 === void 0 ? void 0 : _35.id, (_36 = event === null || event === void 0 ? void 0 : event.detail) === null || _36 === void 0 ? void 0 : _36.data),
        };
      }
      else if (endpoint === "addCompany") {
        data = {
          addCompany: await addCompany(this.db, ((_37 = event === null || event === void 0 ? void 0 : event.detail) === null || _37 === void 0 ? void 0 : _37.data) || ((_38 = event === null || event === void 0 ? void 0 : event.detail) === null || _38 === void 0 ? void 0 : _38.params)),
        };
      }
      else if (endpoint === "editCompany") {
        data = {
          editCompany: await editCompany(this.db, ((_39 = event.detail) === null || _39 === void 0 ? void 0 : _39.id) || ((_41 = (_40 = event === null || event === void 0 ? void 0 : event.detail) === null || _40 === void 0 ? void 0 : _40.params) === null || _41 === void 0 ? void 0 : _41.id), (_42 = event === null || event === void 0 ? void 0 : event.detail) === null || _42 === void 0 ? void 0 : _42.data),
        };
      }
      else if (endpoint === "addTemplate") {
        data = {
          addTemplate: await addTemplate(this.db, ((_43 = event === null || event === void 0 ? void 0 : event.detail) === null || _43 === void 0 ? void 0 : _43.data) || ((_44 = event === null || event === void 0 ? void 0 : event.detail) === null || _44 === void 0 ? void 0 : _44.params)),
        };
      }
      else if (endpoint === "calculateTotaller") {
        data = {
          totals: await calculateTotaller(this.db, (_45 = event === null || event === void 0 ? void 0 : event.detail) === null || _45 === void 0 ? void 0 : _45.data),
        };
      }
      else if (endpoint === "createStripeOAuthToken") {
        data = {
          createStripeOAuthToken: await createStripeOAuthToken(this.db, (_46 = event === null || event === void 0 ? void 0 : event.detail) === null || _46 === void 0 ? void 0 : _46.data),
        };
      }
      else if (endpoint === "addPaymentMethod") {
        data = {
          addPaymentMethod: await addPaymentMethod(this.db, (_47 = event === null || event === void 0 ? void 0 : event.detail) === null || _47 === void 0 ? void 0 : _47.data),
        };
      }
      else if (endpoint === "removePaymentMethod") {
        data = {
          removePaymentMethod: await removePaymentMethod(this.db, (_48 = event === null || event === void 0 ? void 0 : event.detail) === null || _48 === void 0 ? void 0 : _48.data),
        };
      }
      else if (endpoint === "addNote") {
        data = {
          addNote: await addNote(this.db, (_49 = event === null || event === void 0 ? void 0 : event.detail) === null || _49 === void 0 ? void 0 : _49.data),
        };
      }
      else if (endpoint === "deleteNote") {
        data = {
          deleteNote: await deleteNote(this.db, ((_50 = event === null || event === void 0 ? void 0 : event.detail) === null || _50 === void 0 ? void 0 : _50.id) || ((_52 = (_51 = event === null || event === void 0 ? void 0 : event.detail) === null || _51 === void 0 ? void 0 : _51.data) === null || _52 === void 0 ? void 0 : _52.id)),
        };
      }
      else if (endpoint === "setupPayments") {
        if (!((_53 = state === null || state === void 0 ? void 0 : state.session) === null || _53 === void 0 ? void 0 : _53.uid))
          return;
        const data = await createStripeAccountLink(this.db, {
          userId: state.session.uid,
        });
        window.location.href = data.url;
      }
      else if (endpoint === "reorderPins") {
        for (const pin of ((_55 = (_54 = event === null || event === void 0 ? void 0 : event.detail) === null || _54 === void 0 ? void 0 : _54.data) === null || _55 === void 0 ? void 0 : _55.pins) || []) {
          console.log(pin);
          await this.db.update("pins", pin === null || pin === void 0 ? void 0 : pin.id, {
            order: (pin === null || pin === void 0 ? void 0 : pin.order) || 0,
            updatedAt: new Date(),
          });
        }
      }
      else if (endpoint === "exportCsv") {
        data = {
          exportCsv: await this.db.call("exportCsv")({
            data: (_56 = event === null || event === void 0 ? void 0 : event.detail) === null || _56 === void 0 ? void 0 : _56.data,
          }),
        };
      }
      detail.data = data;
    }
    catch (error) {
      console.log("error", error);
      detail.error = { response: { errors: [error] } };
    }
    event.target.dispatchEvent(new CustomEvent((detail === null || detail === void 0 ? void 0 : detail.data) ? "fireenjinSuccess" : "fireenjinError", {
      bubbles: true,
      cancelable: true,
      detail,
    }));
  }
  async onSuccess(event) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
    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 (["addScopeService", "editScopeService", "deleteScopeService"].includes((_b = event === null || event === void 0 ? void 0 : event.detail) === null || _b === void 0 ? void 0 : _b.endpoint)) {
      const job = await findJob(this.db, {
        id: (_c = state === null || state === void 0 ? void 0 : state.job) === null || _c === void 0 ? void 0 : _c.id,
        withPayments: true,
        withUsers: false,
        withSites: true,
        withPayModel: false,
        withPhotos: false,
        withEfiles: true,
        withPayables: false,
        withReadings: false,
      });
      await this.db.update("jobs", (_d = state === null || state === void 0 ? void 0 : state.job) === null || _d === void 0 ? void 0 : _d.id, {
        ...updateJobAmounts(job),
        updatedAt: new Date(),
      });
    }
    else if (["addPin", "deletePin"].includes((_e = event === null || event === void 0 ? void 0 : event.detail) === null || _e === void 0 ? void 0 : _e.endpoint)) {
      this.getPins();
    }
    else if (((_f = event === null || event === void 0 ? void 0 : event.detail) === null || _f === void 0 ? void 0 : _f.endpoint) === "findJob") {
      console.log((_h = (_g = event === null || event === void 0 ? void 0 : event.detail) === null || _g === void 0 ? void 0 : _g.data) === null || _h === void 0 ? void 0 : _h.job);
      state.job = ((_k = (_j = event === null || event === void 0 ? void 0 : event.detail) === null || _j === void 0 ? void 0 : _j.data) === null || _k === void 0 ? void 0 : _k.job) || null;
    }
    else if (((_l = event === null || event === void 0 ? void 0 : event.detail) === null || _l === void 0 ? void 0 : _l.endpoint) === "sendTemplateEmail") {
      this.closeModal();
      this.openToast({
        detail: {
          message: "Email(s) sent!",
          duration: 3000,
        },
      });
    }
  }
  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, _55, _56, _57, _58, _59, _60, _61, _62, _63, _64, _65, _66, _67, _68, _69, _70;
    console.log(event);
    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") {
      if (!((_d = state === null || state === void 0 ? void 0 : state.session) === null || _d === void 0 ? void 0 : _d.uid))
        return;
      const data = await createStripeAccountLink(this.db, {
        userId: state.session.uid,
      });
      window.location.href = data.url;
    }
    else if (triggerName === "export") {
      await downloadCSV({
        data: ((_e = event === null || event === void 0 ? void 0 : event.detail) === null || _e === void 0 ? void 0 : _e.payload) || [],
        filename: ((_f = event === null || event === void 0 ? void 0 : event.detail) === null || _f === void 0 ? void 0 : _f.filename) ||
          `export_${((_g = event === null || event === void 0 ? void 0 : event.detail) === null || _g === void 0 ? void 0 : _g.collection) || "data"}_${new Date().toISOString().split("T")[0]}.csv`,
      });
    }
    else if (triggerName === "import") {
      const files = await openFileSelect();
      importCsvFile(files[0], (_h = event === null || event === void 0 ? void 0 : event.detail) === null || _h === void 0 ? void 0 : _h.type);
    }
    else if (triggerName === "upload") {
      // @TODO Add better error handling and reupload errored ones
      this.uploadQuery = `efile`;
      this.fileInputEl.click();
      this.uploadPath = ((_k = (_j = event === null || event === void 0 ? void 0 : event.detail) === null || _j === void 0 ? void 0 : _j.payload) === null || _k === void 0 ? void 0 : _k.path) || null;
      this.uploadData = {
        tags: ((_m = (_l = event === null || event === void 0 ? void 0 : event.detail) === null || _l === void 0 ? void 0 : _l.payload) === null || _m === void 0 ? void 0 : _m.tags) || [],
        type: ((_p = (_o = event === null || event === void 0 ? void 0 : event.detail) === null || _o === void 0 ? void 0 : _o.payload) === null || _p === void 0 ? void 0 : _p.type) || "upload",
        jobId: ((_r = (_q = event === null || event === void 0 ? void 0 : event.detail) === null || _q === void 0 ? void 0 : _q.payload) === null || _r === void 0 ? void 0 : _r.jobId) || null,
      };
    }
    else if (triggerName === "photos") {
      // @TODO Add better error handling and reupload errored ones
      this.uploadQuery = `photo`;
      this.uploadPath = ((_t = (_s = event === null || event === void 0 ? void 0 : event.detail) === null || _s === void 0 ? void 0 : _s.payload) === null || _t === void 0 ? void 0 : _t.path) || null;
      this.fileInputEl.click();
      this.uploadData = {
        default: !!((_v = (_u = event === null || event === void 0 ? void 0 : event.detail) === null || _u === void 0 ? void 0 : _u.payload) === null || _v === void 0 ? void 0 : _v.default),
        tags: ((_x = (_w = event === null || event === void 0 ? void 0 : event.detail) === null || _w === void 0 ? void 0 : _w.payload) === null || _x === void 0 ? void 0 : _x.tags) || [],
        jobId: ((_z = (_y = event === null || event === void 0 ? void 0 : event.detail) === null || _y === void 0 ? void 0 : _y.payload) === null || _z === void 0 ? void 0 : _z.jobId) || null,
        siteId: ((_1 = (_0 = event === null || event === void 0 ? void 0 : event.detail) === null || _0 === void 0 ? void 0 : _0.payload) === null || _1 === void 0 ? void 0 : _1.siteId) || null,
        inventoryId: ((_3 = (_2 = event === null || event === void 0 ? void 0 : event.detail) === null || _2 === void 0 ? void 0 : _2.payload) === null || _3 === void 0 ? void 0 : _3.inventoryId) || null,
        serviceId: ((_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.serviceId) || null,
      };
    }
    else if (["sort", "filter", "move"].includes(triggerName)) {
      let data = ((_8 = (_7 = (_6 = event === null || event === void 0 ? void 0 : event.detail) === null || _6 === void 0 ? void 0 : _6.payload) === null || _7 === void 0 ? void 0 : _7.control) === null || _8 === void 0 ? void 0 : _8.options)
        ? event.detail.payload.control.options.map((option) => ({
          text: option.label,
          value: option.value,
          group: option.group,
        }))
        : [];
      if (!(data === null || data === void 0 ? void 0 : data.length) && ((_11 = (_10 = (_9 = event === null || event === void 0 ? void 0 : event.detail) === null || _9 === void 0 ? void 0 : _9.payload) === null || _10 === void 0 ? void 0 : _10.control) === null || _11 === void 0 ? void 0 : _11.endpoint)) {
        const response = await this.db.call(event.detail.payload.control.endpoint)(((_14 = (_13 = (_12 = event === null || event === void 0 ? void 0 : event.detail) === null || _12 === void 0 ? void 0 : _12.payload) === null || _13 === void 0 ? void 0 : _13.control) === null || _14 === void 0 ? void 0 : _14.params) || {});
        const results = response[((_17 = (_16 = (_15 = event === null || event === void 0 ? void 0 : event.detail) === null || _15 === void 0 ? void 0 : _15.payload) === null || _16 === void 0 ? void 0 : _16.control) === null || _17 === void 0 ? void 0 : _17.resultsKey)
          ? event.detail.payload.control.resultsKey
          : (_20 = (_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.control) === null || _20 === void 0 ? void 0 : _20.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: !!((_22 = (_21 = event === null || event === void 0 ? void 0 : event.detail) === null || _21 === void 0 ? void 0 : _21.payload) === null || _22 === void 0 ? void 0 : _22.filter),
        filterEmptyText: ((_24 = (_23 = event === null || event === void 0 ? void 0 : event.detail) === null || _23 === void 0 ? void 0 : _23.payload) === null || _24 === void 0 ? void 0 : _24.filterEmptyText) || null,
        filterPlaceholderText: ((_26 = (_25 = event === null || event === void 0 ? void 0 : event.detail) === null || _25 === void 0 ? void 0 : _25.payload) === null || _26 === void 0 ? void 0 : _26.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 ((_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.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",
              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: !!((_31 = (_30 = (_29 = event === null || event === void 0 ? void 0 : event.detail) === null || _29 === void 0 ? void 0 : _29.payload) === null || _30 === void 0 ? void 0 : _30.control) === null || _31 === void 0 ? void 0 : _31.multiple),
        data,
      });
      this.floatSelect.setVal((_34 = (_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.control) === null || _34 === void 0 ? void 0 : _34.value);
      this.floatSelect.open();
    }
    else if (triggerName === "login") {
      const type = ((_36 = (_35 = event === null || event === void 0 ? void 0 : event.detail) === null || _35 === void 0 ? void 0 : _35.payload) === null || _36 === void 0 ? void 0 : _36.type) || "email";
      let res;
      if (type === "email") {
        res = await this.auth.withEmailLink((_38 = (_37 = event === null || event === void 0 ? void 0 : event.detail) === null || _37 === void 0 ? void 0 : _37.payload) === null || _38 === void 0 ? void 0 : _38.email, {
          url: (_39 = state === null || state === void 0 ? void 0 : state.config) === null || _39 === void 0 ? void 0 : _39.url,
          dynamicLinkDomain: (_40 = state === null || state === void 0 ? void 0 : state.config) === null || _40 === void 0 ? void 0 : _40.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", ((_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.token) || getParameter("token"))).data();
        res = await this.auth.withToken(tempToken.token);
      }
      else {
        res = await this.auth.withSocial(type);
      }
      if ((_43 = res === null || res === void 0 ? void 0 : res.user) === null || _43 === void 0 ? void 0 : _43.uid) {
        const routerEl = document.querySelector("ion-router");
        routerEl.push("dashboard");
      }
    }
    else if (triggerName === "subscribe") {
      this.db.watchDocument((_45 = (_44 = event === null || event === void 0 ? void 0 : event.detail) === null || _44 === void 0 ? void 0 : _44.payload) === null || _45 === void 0 ? void 0 : _45.collection, (_47 = (_46 = event === null || event === void 0 ? void 0 : event.detail) === null || _46 === void 0 ? void 0 : _46.payload) === null || _47 === void 0 ? void 0 : _47.id, typeof ((_49 = (_48 = event === null || event === void 0 ? void 0 : event.detail) === null || _48 === void 0 ? void 0 : _48.payload) === null || _49 === void 0 ? void 0 : _49.callback) === "function"
        ? (_51 = (_50 = event === null || event === void 0 ? void 0 : event.detail) === null || _50 === void 0 ? void 0 : _50.payload) === null || _51 === void 0 ? void 0 : _51.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((_53 = (_52 = event === null || event === void 0 ? void 0 : event.detail) === null || _52 === void 0 ? void 0 : _52.payload) === null || _53 === void 0 ? void 0 : _53.collection, (_55 = (_54 = event === null || event === void 0 ? void 0 : event.detail) === null || _54 === void 0 ? void 0 : _54.payload) === null || _55 === void 0 ? void 0 : _55.id);
    }
    else if (triggerName === "set") {
      if (((_58 = (_57 = (_56 = event === null || event === void 0 ? void 0 : event.detail) === null || _56 === void 0 ? void 0 : _56.event) === null || _57 === void 0 ? void 0 : _57.detail) === null || _58 === void 0 ? void 0 : _58.type) === "feedType") {
        const value = ((_60 = (_59 = event.detail) === null || _59 === void 0 ? void 0 : _59.payload) === null || _60 === void 0 ? void 0 : _60.value) || [];
        const type = value.filter((typeStr) => typeStr !== "me" && !typeStr.includes("location-"));
        const locationsFeed = value
          .filter((typeStr) => typeStr.includes("location-"))
          .map((locationStr) => locationStr.replace("location-", ""));
        state.feedFetchData = {
          ...state === null || state === void 0 ? void 0 : state.feedFetchData,
          myFeed: value.includes("me"),
          locationsFeed,
          type,
        };
        // const activityFeedEl = document.getElementById(
        //   "activity-feed"
        // ) as HTMLFireenjinPaginationElement;
        // if (activityFeedEl?.getResults) activityFeedEl.getResults();
        return;
      }
      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][(_62 = (_61 = event === null || event === void 0 ? void 0 : event.detail) === null || _61 === void 0 ? void 0 : _61.payload) === null || _62 === void 0 ? void 0 : _62.name] =
        (_64 = (_63 = event === null || event === void 0 ? void 0 : event.detail) === null || _63 === void 0 ? void 0 : _63.payload) === null || _64 === void 0 ? void 0 : _64.value;
      state.filters = { ...state.filters };
      console.log(state.filters);
    }
    else if (triggerName === "select") {
      if (((_66 = (_65 = event === null || event === void 0 ? void 0 : event.detail) === null || _65 === void 0 ? void 0 : _65.payload) === null || _66 === void 0 ? void 0 : _66.name) === "status") {
        await editJob(this.db, (_68 = (_67 = event === null || event === void 0 ? void 0 : event.detail) === null || _67 === void 0 ? void 0 : _67.el) === null || _68 === void 0 ? void 0 : _68.jobId, {
          status: (_70 = (_69 = event === null || event === void 0 ? void 0 : event.detail) === null || _69 === void 0 ? void 0 : _69.payload) === null || _70 === void 0 ? void 0 : _70.value,
        });
      }
    }
  }
  closeModal() {
    const modalEls = document.querySelectorAll("ion-modal");
    if (modalEls) {
      modalEls.forEach((modalEl) => modalEl.dismiss());
    }
    state.site = null;
    this.modal = null;
  }
  async openModal(event) {
    console.log(event.detail);
    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;
    let stopLoader = true;
    if (!Build.isBrowser)
      return false;
    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 (!((_a = state === null || state === void 0 ? void 0 : state.session) === null || _a === void 0 ? void 0 : _a.uid) && ["/dashboard"].indexOf(event.detail.to) >= 0) {
      stopLoader = false;
      if (this.routerEl)
        this.routerEl.push("/");
    }
    if (stopLoader) {
      document.body.classList.add("is-loaded");
    }
  }
  async uploadFiles(event) {
    var _a, _b;
    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: this.uploadPath,
      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 === "efile") {
        data.name = (file === null || file === void 0 ? void 0 : file.name) || new Date().toDateString();
        await addEfile(this.db, data);
      }
      else {
        console.log("addPhoto", data);
        await addPhoto(this.db, data);
      }
    }
    this.closeToast();
  }
  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",
          id: currentPin.id,
        });
      }
      else {
        this.fireenjinSubmit.emit({
          endpoint: "addPin",
          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");
      state.templates = await linkTemplatesToPartials(templates || []);
    }
    catch (_a) {
      console.log("Error loading templates");
    }
  }
  async getPaymentMethods() {
    var _a;
    try {
      state.paymentMethods = await this.db.list(`/users/${(_a = state === null || state === void 0 ? void 0 : state.session) === null || _a === void 0 ? void 0 : _a.uid}/paymentMethods`, null);
    }
    catch (e) {
      console.log("Error getting payment methods", e);
    }
    return state.paymentMethods;
  }
  async getLocations() {
    try {
      state.locations = await listLocations(this.db);
    }
    catch (e) {
      console.log("Error getting locations", e);
    }
    return state.locations;
  }
  async getServices() {
    try {
      state.services = await listServices(this.db);
    }
    catch (e) {
      console.log("Error getting services", e);
    }
    return state.services;
  }
  async getMyJobs() {
    var _a;
    let jobs = [];
    try {
      jobs = await listJobs(this.db, {
        data: { userId: (_a = state === null || state === void 0 ? void 0 : state.session) === null || _a === void 0 ? void 0 : _a.uid },
        withPayables: true,
      });
    }
    catch (e) {
      console.log("Error getting my jobs", e);
    }
    return jobs;
  }
  async getPins() {
    var _a;
    try {
      const pins = await listPins(this.db, {
        data: { userId: (_a = state === null || state === void 0 ? void 0 : state.session) === null || _a === void 0 ? void 0 : _a.uid },
      });
      state.pins = pins.sort((a, b) => a.order - b.order);
      console.log(state.pins);
    }
    catch (e) {
      console.log("Error getting my pins", e);
    }
    return state.pins;
  }
  async getManifest() {
    const response = await fetch("/manifest.json");
    const json = await response.json();
    return json;
  }
  async 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);
    }
    state.claims = (await getCache("floodteam:claims")) || {};
    state.filters = (await getCache("floodteam:filters")) || {};
    this.getLocations();
    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) {
        state.feedFetchData.myFeed = session === null || session === void 0 ? void 0 : session.uid;
        state.services = (await getCache("floodteam:services")) || [];
        state.jobs = (await getCache("floodteam:jobs")) || {};
        state.users = (await getCache("floodteam:users")) || {};
        state.pins = (await getCache("floodteam:pins")) || [];
        state.profile = (await getCache("floodteam:profile")) || null;
        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,
          });
        }
        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.getServices();
        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.getPaymentMethods();
          this.getMyJobs();
          this.getPins();
          const activityFeedEl = document.getElementById("activity-feed");
          if (activityFeedEl === null || activityFeedEl === void 0 ? void 0 : activityFeedEl.getResults)
            activityFeedEl.getResults();
        });
      }
    });
  }
  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", componentProps: { app: this.app } }), 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", componentProps: { db: this.db } }), 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", componentProps: { db: this.db } }), 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: "/jobs/agent", component: "app-job-new", componentProps: { agent: true } }), h("ion-route", { url: "/jobs/agent/:agentId", component: "app-job-new", componentProps: { agent: 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": "fireenjinFetch",
        "method": "onFetch",
        "target": "document",
        "capture": false,
        "passive": false
      }, {
        "name": "fireenjinSubmit",
        "method": "onSubmit",
        "target": "document",
        "capture": false,
        "passive": false
      }, {
        "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
      }];
  }
}
