import { Build, 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 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";
import removeSignaturesFromEfiles from "../contracts/efile/removeSignaturesFromEfiles";
import listFlows from "../contracts/flow/listFlows";
import listSteps from "../contracts/step/listSteps";
import addStep from "../contracts/step/addStep";
import addFlow from "../contracts/flow/addFlow";
import deleteStep from "../contracts/step/deleteStep";
import deleteFlow from "../contracts/flow/deleteFlow";
import findStep from "../contracts/step/findStep";
import findFlow from "../contracts/flow/findFlow";
import editFlow from "../contracts/flow/editFlow";
import editStep from "../contracts/step/editStep";
import addDot from "../contracts/dot/addDot";
import editDot from "../contracts/dot/editDot";
import deleteDot from "../contracts/dot/deleteDot";
import findDot from "../contracts/dot/findDot";
import listDots from "../contracts/dot/listDots";
import addWeather from "../contracts/weather/addWeather";
import addService from "../contracts/services/addService";
import editService from "../contracts/services/editService";
import deleteTemplate from "../contracts/template/deleteTemplate";
import addTest from "../contracts/test/addTest";
import editTest from "../contracts/test/editTest";
import listTests from "../contracts/test/listTests";
import findTest from "../contracts/test/findTest";
import addMaterial from "../contracts/material/addMaterial";
import editMaterial from "../contracts/material/editMaterial";
import findMaterial from "../contracts/material/findMaterial";
import listMaterials from "../contracts/material/listMaterials";
import addInventory from "../contracts/inventory/addInventory";
import editInventory from "../contracts/inventory/editInventory";
import findInventory from "../contracts/inventory/findInventory";
import listInventories from "../contracts/inventory/listInventories";
import addEquipment from "../contracts/equipment/addEquipment";
import editEquipment from "../contracts/equipment/editEquipment";
import findEquipment from "../contracts/equipment/findEquipment";
import listEquipment from "../contracts/equipment/listEquipment";
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.fireenjin = new FireEnjin({
      debug: true,
      connections: [
        {
          type: "firebase",
          url: "",
          db: this.db,
          name: "default",
        },
      ],
      onFetch: async (endpoint, input, options) => {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v;
        if (endpoint === "findJob") {
          return {
            job: await findJob(this.db, input)
          };
        }
        else if (endpoint === "listJobs") {
          return {
            jobs: ((_b = (_a = input === null || input === void 0 ? void 0 : input.data) === null || _a === void 0 ? void 0 : _a.query) === null || _b === void 0 ? void 0 : _b.length)
              ? await searchJobs(input === null || input === void 0 ? void 0 : input.data, {
                algoliaId: (_d = (_c = state === null || state === void 0 ? void 0 : state.config) === null || _c === void 0 ? void 0 : _c.algolia) === null || _d === void 0 ? void 0 : _d.appId,
                algoliaKey: (_f = (_e = state === null || state === void 0 ? void 0 : state.config) === null || _e === void 0 ? void 0 : _e.algolia) === null || _f === void 0 ? void 0 : _f.searchKey,
              })
              : await listJobs(this.db, input),
          };
        }
        else if (endpoint === "findTotaller") {
          return {
            totaller: await findTotaller(this.db, input.id || (input === null || input === void 0 ? void 0 : input.id)),
          };
        }
        else if (endpoint === "listTotallers") {
          return {
            totallers: await listTotallers(this.db, input),
          };
        }
        else if (endpoint === "listFlows") {
          return {
            flows: await listFlows(this.db, input),
          };
        }
        else if (endpoint === "listSteps") {
          return {
            steps: await listSteps(this.db, input),
          };
        }
        else if (endpoint === "listAlerts") {
          return {
            alerts: await listAlerts(this.db, input),
          };
        }
        else if (endpoint === "findLocation") {
          return {
            location: await findLocation(this.db, input.id || (input === null || input === void 0 ? void 0 : input.id)),
          };
        }
        else if (endpoint === "findFlow") {
          return {
            flow: await findFlow(this.db, input.id || (input === null || input === void 0 ? void 0 : input.id), input === null || input === void 0 ? void 0 : input.renderId),
          };
        }
        else if (endpoint === "findStep") {
          return {
            step: await findStep(this.db, input.id || (input === null || input === void 0 ? void 0 : input.id)),
          };
        }
        else if (endpoint === "findTemplate") {
          return {
            template: await findTemplate(this.db, input.id || (input === null || input === void 0 ? void 0 : input.id)),
          };
        }
        else if (endpoint === "listLocations") {
          return {
            locations: await listLocations(this.db, input),
          };
        }
        else if (endpoint === "listPayments") {
          return {
            payments: await listPayment(this.db, input),
          };
        }
        else if (endpoint === "findCompany") {
          return {
            company: await findCompany(this.db, input.id || (input === null || input === void 0 ? void 0 : input.id)),
          };
        }
        else if (endpoint === "listCompanies") {
          return {
            companies: await listCompanies(this.db, input),
          };
        }
        else if (endpoint === "findEquipment") {
          return {
            equipment: await findEquipment(this.db, input.id || (input === null || input === void 0 ? void 0 : input.id)),
          };
        }
        else if (endpoint === "listEquipment") {
          return {
            equipment: await listEquipment(this.db, input),
          };
        }
        else if (endpoint === "findInventory") {
          return {
            inventory: await findInventory(this.db, input.id || (input === null || input === void 0 ? void 0 : input.id)),
          };
        }
        else if (endpoint === "listInventories") {
          return {
            inventories: await listInventories(this.db, input),
          };
        }
        else if (endpoint === "findMaterial") {
          return {
            material: await findMaterial(this.db, input.id || (input === null || input === void 0 ? void 0 : input.id)),
          };
        }
        else if (endpoint === "listMaterials") {
          return {
            materials: await listMaterials(this.db, input),
          };
        }
        else if (endpoint === "findDot") {
          return {
            dot: await findDot(this.db, input.id || (input === null || input === void 0 ? void 0 : input.id)),
          };
        }
        else if (endpoint === "listDots") {
          return {
            dots: await listDots(this.db, input),
          };
        }
        else if (endpoint === "findUser") {
          return {
            user: await findUser(this.db, input.id || (input === null || input === void 0 ? void 0 : input.id)),
          };
        }
        else if (endpoint === "listUsers") {
          return {
            users: ((_h = (_g = input === null || input === void 0 ? void 0 : input.data) === null || _g === void 0 ? void 0 : _g.query) === null || _h === void 0 ? void 0 : _h.length)
              ? await searchUsers(input === null || input === void 0 ? void 0 : input.data, {
                algoliaId: (_k = (_j = state === null || state === void 0 ? void 0 : state.config) === null || _j === void 0 ? void 0 : _j.algolia) === null || _k === void 0 ? void 0 : _k.appId,
                algoliaKey: (_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.searchKey,
              })
              : await listUsers(this.db, input),
          };
        }
        else if (endpoint === "listSites") {
          return {
            sites: await listSites(this.db, input),
          };
        }
        else if (endpoint === "findSite") {
          return {
            site: await findSite(this.db, input.id || (input === null || input === void 0 ? void 0 : input.id)),
          };
        }
        else if (endpoint === "listTriggers") {
          return {
            triggers: await listTriggers(this.db, input),
          };
        }
        else if (endpoint === "findTrigger") {
          return {
            trigger: await findTrigger(this.db, input.id || (input === null || input === void 0 ? void 0 : input.id)),
          };
        }
        else if (endpoint === "listDots") {
          return {
            dots: await listDots(this.db, input),
          };
        }
        else if (endpoint === "findDot") {
          return {
            test: await findDot(this.db, input.id || (input === null || input === void 0 ? void 0 : input.id)),
          };
        }
        else if (endpoint === "listTests") {
          return {
            tests: await listTests(this.db, input),
          };
        }
        else if (endpoint === "findTest") {
          return {
            dot: await findTest(this.db, input.id || (input === null || input === void 0 ? void 0 : input.id), input === null || input === void 0 ? void 0 : input.flowId),
          };
        }
        else if (endpoint === "findTotals") {
          return {
            totals: await findTotals(this.db, input === null || input === void 0 ? void 0 : input.path),
          };
        }
        else if (endpoint === "listTotals") {
          return {
            totals: await listTotals(this.db, input === null || input === void 0 ? void 0 : input.path),
          };
        }
        else if (endpoint === "listWeather") {
          return {
            weather: await listWeather(this.db, input),
          };
        }
        else if (endpoint === "listExhausts") {
          return {
            exhausts: await listExhausts(this.db, input),
          };
        }
        else if (endpoint === "listVehicles") {
          return {
            vehicles: await listVehicles(this.db, input),
          };
        }
        else if (endpoint === "listPhoneNumbers") {
          return {
            phoneNumbers: await listPhoneNumbers(this.db, input),
          };
        }
        else if (endpoint === "listPaymentMethods") {
          return {
            paymentMethods: await this.getPaymentMethods(),
          };
        }
        else if (endpoint === "listFeeds") {
          return {
            feeds: await listFeeds(this.db, input === null || input === void 0 ? void 0 : input.data),
          };
        }
        else if (endpoint === "listServices") {
          return {
            services: await listServices(this.db, input),
          };
        }
        else if (endpoint === "searchUsers") {
          return {
            users: await searchUsers(input, {
              algoliaId: (_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.appId,
              algoliaKey: (_r = (_q = state === null || state === void 0 ? void 0 : state.config) === null || _q === void 0 ? void 0 : _q.algolia) === null || _r === void 0 ? void 0 : _r.searchKey,
            }),
          };
        }
        else if (endpoint === "searchJobs") {
          return {
            jobs: await searchJobs(input, {
              algoliaId: (_t = (_s = state === null || state === void 0 ? void 0 : state.config) === null || _s === void 0 ? void 0 : _s.algolia) === null || _t === void 0 ? void 0 : _t.appId,
              algoliaKey: (_v = (_u = state === null || state === void 0 ? void 0 : state.config) === null || _u === void 0 ? void 0 : _u.algolia) === null || _v === void 0 ? void 0 : _v.searchKey,
            }),
          };
        }
        return options.fn(endpoint, input, options);
      },
      onSubmit: async (endpoint, input, options) => {
        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;
        if (endpoint === "addJob") {
          return {
            addJob: await addJob(this.db, input.data),
          };
        }
        else if (endpoint === "addWeather") {
          return {
            addWeather: await addWeather(this.db, input.data),
          };
        }
        else if (endpoint === "editJob") {
          return {
            editJob: await editJob(this.db, (input === null || input === void 0 ? void 0 : input.id) || ((_a = input.params) === null || _a === void 0 ? void 0 : _a.id), input.data),
          };
        }
        else if (endpoint === "addLocation") {
          return {
            addLocation: await addLocation(this.db, input.data),
          };
        }
        else if (endpoint === "editLocation") {
          return {
            editLocation: await editLocation(this.db, (input === null || input === void 0 ? void 0 : input.id) || ((_b = input.params) === null || _b === void 0 ? void 0 : _b.id), input.data),
          };
        }
        else if (endpoint === "editFlow") {
          return {
            editFlow: await editFlow(this.db, (input === null || input === void 0 ? void 0 : input.id) || ((_c = input.params) === null || _c === void 0 ? void 0 : _c.id), input.data),
          };
        }
        else if (endpoint === "editStep") {
          return {
            editStep: await editStep(this.db, (input === null || input === void 0 ? void 0 : input.id) || ((_d = input.params) === null || _d === void 0 ? void 0 : _d.id), input.data),
          };
        }
        else if (endpoint === "editService") {
          return {
            editService: await editService(this.db, (input === null || input === void 0 ? void 0 : input.id) || ((_e = input.params) === null || _e === void 0 ? void 0 : _e.id), input.data),
          };
        }
        else if (endpoint === "editTrigger") {
          return {
            editTrigger: await editTrigger(this.db, (input === null || input === void 0 ? void 0 : input.id) || ((_f = input.params) === null || _f === void 0 ? void 0 : _f.id), input.data),
          };
        }
        else if (endpoint === "addAlert") {
          return {
            addAlert: await addAlert(this.db, input.data),
          };
        }
        else if (endpoint === "addFlow") {
          return {
            addFlow: await addFlow(this.db, input.data),
          };
        }
        else if (endpoint === "addService") {
          return {
            addService: await addService(this.db, input.data),
          };
        }
        else if (endpoint === "addStep") {
          return {
            addStep: await addStep(this.db, input.data),
          };
        }
        else if (endpoint === "addTrigger") {
          return {
            addTrigger: await addTrigger(this.db, input.data),
          };
        }
        else if (endpoint === "editTotaller") {
          return {
            editTotaller: await editTotaller(this.db, (input === null || input === void 0 ? void 0 : input.id) || ((_g = input.params) === null || _g === void 0 ? void 0 : _g.id), input.data),
          };
        }
        else if (endpoint === "addTotaller") {
          return {
            addTotaller: await addTotaller(this.db, input.data),
          };
        }
        else if (endpoint === "addPayment") {
          return {
            addPayment: await addPayment(this.db, input.data),
          };
        }
        else if (endpoint === "addSite") {
          return {
            addSite: await addSite(this.db, input.data),
          };
        }
        else if (endpoint === "editSite") {
          return {
            editSite: await editSite(this.db, (input === null || input === void 0 ? void 0 : input.id) || ((_h = input.params) === null || _h === void 0 ? void 0 : _h.id), input.data),
          };
        }
        else if (endpoint === "addPin") {
          return {
            addPin: await addPin(this.db, input.data),
          };
        }
        else if (endpoint === "addScopeService") {
          return {
            addScopeService: await addScopeService(this.db, input.data),
          };
        }
        else if (endpoint === "editScopeService") {
          return {
            editScopeService: await editScopeService(this.db, input === null || input === void 0 ? void 0 : input.data),
          };
        }
        else if (endpoint === "deleteScopeService") {
          return {
            deleteScopeService: await deleteScopeService(this.db, input === null || input === void 0 ? void 0 : input.data),
          };
        }
        else if (endpoint === "deleteFlow") {
          return {
            deleteFlow: await deleteFlow(this.db, input === null || input === void 0 ? void 0 : input.data),
          };
        }
        else if (endpoint === "deleteStep") {
          return {
            deleteStep: await deleteStep(this.db, (_j = input === null || input === void 0 ? void 0 : input.data) === null || _j === void 0 ? void 0 : _j.id),
          };
        }
        else if (endpoint === "addUserToJob") {
          return {
            addUserToJob: await addUserToJob(this.db, input === null || input === void 0 ? void 0 : input.data),
          };
        }
        else if (endpoint === "removeUserFromJob") {
          return {
            removeUserFromJob: await removeUserFromJob(this.db, input === null || input === void 0 ? void 0 : input.data),
          };
        }
        else if (endpoint === "removeSignaturesFromEfiles") {
          return {
            removeSignaturesFromEfiles: await removeSignaturesFromEfiles(this.db, input === null || input === void 0 ? void 0 : input.data),
          };
        }
        else if (endpoint === "addUser") {
          return {
            addUser: await addUser(this.db, input.data),
          };
        }
        else if (endpoint === "editUser") {
          return {
            editUser: await editUser(this.db, (input === null || input === void 0 ? void 0 : input.id) || ((_k = input.params) === null || _k === void 0 ? void 0 : _k.id), input.data),
          };
        }
        else if (endpoint === "generatePdf") {
          return {
            generatePdf: await generatePdf(this.db, ((_l = input.params) === null || _l === void 0 ? void 0 : _l.data) || input.data),
          };
        }
        else if (endpoint === "signContract") {
          return {
            signContract: await signContract(this.db, input.data),
          };
        }
        else if (endpoint === "sendTemplateEmail") {
          return {
            sendTemplateEmail: await sendTemplateEmail(this.db, input.data),
          };
        }
        else if (endpoint === "deleteSite") {
          if ((_m = state === null || state === void 0 ? void 0 : state.job) === null || _m === void 0 ? void 0 : _m.sites) {
            state.job.sites = (((_o = state === null || state === void 0 ? void 0 : state.job) === null || _o === void 0 ? void 0 : _o.sites) || []).filter((site) => { var _a; return (site === null || site === void 0 ? void 0 : site.id) !== ((_a = input.data) === null || _a === void 0 ? void 0 : _a.id); });
            state.job = { ...state.job };
          }
          return {
            deleteSite: await deleteSite(this.db, (_p = input.data) === null || _p === void 0 ? void 0 : _p.id),
          };
        }
        else if (endpoint === "deleteEfile") {
          return {
            deleteEfile: await deleteEfile(this.db, input.id),
          };
        }
        else if (endpoint === "editPhoto") {
          return {
            deletePhoto: await editPhoto(this.db, input.id, input.data),
          };
        }
        else if (endpoint === "deletePhoto") {
          return {
            deletePhoto: await deletePhoto(this.db, input.id),
          };
        }
        else if (endpoint === "deletePin") {
          return {
            deletePin: await deletePin(this.db, input.id),
          };
        }
        else if (endpoint === "editTemplate") {
          const template = await editTemplate(this.db, input.id || ((_q = input.params) === null || _q === void 0 ? void 0 : _q.id), input.data);
          this.getTemplates();
          return {
            editTemplate: template
          };
        }
        else if (endpoint === "deleteTemplate") {
          const template = await deleteTemplate(this.db, input.id || ((_r = input.params) === null || _r === void 0 ? void 0 : _r.id));
          this.getTemplates();
          return {
            deleteTemplate: template
          };
        }
        else if (endpoint === "editDot") {
          return {
            editDot: await editDot(this.db, input.id || ((_s = input.params) === null || _s === void 0 ? void 0 : _s.id), input.data),
          };
        }
        else if (endpoint === "addTemplate") {
          const template = await addTemplate(this.db, input.data);
          this.getTemplates();
          return {
            addTemplate: template
          };
        }
        else if (endpoint === "addDot") {
          return {
            addDot: await addDot(this.db, input.data || input.params),
          };
        }
        else if (endpoint === "editDot") {
          return {
            editDot: await editDot(this.db, (input === null || input === void 0 ? void 0 : input.id) || ((_t = input.params) === null || _t === void 0 ? void 0 : _t.id), input.data),
          };
        }
        else if (endpoint === "deleteDot") {
          return {
            deleteDot: await deleteDot(this.db, input.id || ((_u = input.data) === null || _u === void 0 ? void 0 : _u.id)),
          };
        }
        else if (endpoint === "addCompany") {
          return {
            addCompany: await addCompany(this.db, input.data || input.params),
          };
        }
        else if (endpoint === "editCompany") {
          return {
            editCompany: await editCompany(this.db, (input === null || input === void 0 ? void 0 : input.id) || ((_v = input.params) === null || _v === void 0 ? void 0 : _v.id), input.data),
          };
        }
        else if (endpoint === "addEquipment") {
          return {
            addEquipment: await addEquipment(this.db, input.data || input.params),
          };
        }
        else if (endpoint === "editEquipment") {
          return {
            editEquipment: await editEquipment(this.db, (input === null || input === void 0 ? void 0 : input.id) || ((_w = input.params) === null || _w === void 0 ? void 0 : _w.id), input.data),
          };
        }
        else if (endpoint === "addInventory") {
          return {
            addInventory: await addInventory(this.db, input.data || input.params),
          };
        }
        else if (endpoint === "editInventory") {
          return {
            editInventory: await editInventory(this.db, (input === null || input === void 0 ? void 0 : input.id) || ((_x = input.params) === null || _x === void 0 ? void 0 : _x.id), input.data),
          };
        }
        else if (endpoint === "addMaterial") {
          return {
            addMaterial: await addMaterial(this.db, input.data || input.params),
          };
        }
        else if (endpoint === "editMaterial") {
          return {
            editMaterial: await editMaterial(this.db, (input === null || input === void 0 ? void 0 : input.id) || ((_y = input === null || input === void 0 ? void 0 : input.params) === null || _y === void 0 ? void 0 : _y.id), input.data),
          };
        }
        else if (endpoint === "addTemplate") {
          return {
            addTemplate: await addTemplate(this.db, input.data || input.params),
          };
        }
        else if (endpoint === "calculateTotaller") {
          return {
            totals: await calculateTotaller(this.db, input.data),
          };
        }
        else if (endpoint === "createStripeOAuthToken") {
          return {
            createStripeOAuthToken: await createStripeOAuthToken(this.db, input.data),
          };
        }
        else if (endpoint === "addPaymentMethod") {
          return {
            addPaymentMethod: await addPaymentMethod(this.db, input.data),
          };
        }
        else if (endpoint === "removePaymentMethod") {
          return {
            removePaymentMethod: await removePaymentMethod(this.db, input.data),
          };
        }
        else if (endpoint === "addNote") {
          return {
            addNote: await addNote(this.db, input.data),
          };
        }
        else if (endpoint === "deleteNote") {
          return {
            deleteNote: await deleteNote(this.db, input.id || ((_z = input.data) === null || _z === void 0 ? void 0 : _z.id)),
          };
        }
        else if (endpoint === "setupPayments") {
          if (!((_0 = state === null || state === void 0 ? void 0 : state.session) === null || _0 === void 0 ? void 0 : _0.uid))
            return;
          const { url } = await createStripeAccountLink(this.db, {
            userId: state.session.uid,
          });
          window.location.href = url;
          return { url };
        }
        else if (endpoint === "reorderPins") {
          for (const pin of ((_1 = input.data) === null || _1 === void 0 ? void 0 : _1.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") {
          return {
            exportCsv: await this.db.call("exportCsv")({
              data: input.data,
            }),
          };
        }
        else if (endpoint === "addTest") {
          return {
            addTest: await addTest(this.db, input.data),
          };
        }
        else if (endpoint === "editTest") {
          return {
            editTest: await editTest(this.db, (input === null || input === void 0 ? void 0 : input.id) || ((_2 = input.params) === null || _2 === void 0 ? void 0 : _2.id), input.data),
          };
        }
        return options.fn(endpoint, input, options);
      }
    });
    this.uploadData = {};
  }
  async onSuccess(event) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
    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") {
      state.job = ((_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) || null;
      state.jobs[(_l = (_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 || _l === void 0 ? void 0 : _l.id] = ((_o = (_m = event === null || event === void 0 ? void 0 : event.detail) === null || _m === void 0 ? void 0 : _m.data) === null || _o === void 0 ? void 0 : _o.job) || null;
    }
    else if (((_p = event === null || event === void 0 ? void 0 : event.detail) === null || _p === void 0 ? void 0 : _p.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, _71, _72, _73, _74, _75;
    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({
        collection: (_e = event === null || event === void 0 ? void 0 : event.detail) === null || _e === void 0 ? void 0 : _e.collection,
        filters: (_f = event === null || event === void 0 ? void 0 : event.detail) === null || _f === void 0 ? void 0 : _f.filters,
        filename: ((_g = event === null || event === void 0 ? void 0 : event.detail) === null || _g === void 0 ? void 0 : _g.filename) ||
          `export_${((_h = event === null || event === void 0 ? void 0 : event.detail) === null || _h === void 0 ? void 0 : _h.collection) || "data"}_${new Date().toISOString().split("T")[0]}.csv`,
      }, { db: this.db });
    }
    else if (triggerName === "import") {
      const files = await openFileSelect();
      importCsvFile(files[0], (_j = event === null || event === void 0 ? void 0 : event.detail) === null || _j === void 0 ? void 0 : _j.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.matchKey, (_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.importTypes);
    }
    else if (triggerName === "upload") {
      // @TODO Add better error handling and reupload errored ones
      this.uploadQuery = `efile`;
      this.fileInputEl.click();
      this.uploadPath = ((_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.path) || null;
      this.uploadData = {
        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) || [],
        type: ((_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.type) || "upload",
        jobId: ((_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.jobId) || null,
      };
    }
    else if (triggerName === "photos") {
      // @TODO Add better error handling and reupload errored ones
      this.uploadQuery = `photo`;
      this.uploadPath = ((_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.path) || null;
      this.fileInputEl.click();
      this.uploadData = {
        default: !!((_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.default),
        tags: ((_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.tags) || [],
        jobId: ((_4 = (_3 = event === null || event === void 0 ? void 0 : event.detail) === null || _3 === void 0 ? void 0 : _3.payload) === null || _4 === void 0 ? void 0 : _4.jobId) || null,
        siteId: ((_6 = (_5 = event === null || event === void 0 ? void 0 : event.detail) === null || _5 === void 0 ? void 0 : _5.payload) === null || _6 === void 0 ? void 0 : _6.siteId) || null,
        inventoryId: ((_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.inventoryId) || null,
        serviceId: ((_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.serviceId) || null,
      };
    }
    else if (["sort", "filter", "move"].includes(triggerName)) {
      let data = ((_13 = (_12 = (_11 = event === null || event === void 0 ? void 0 : event.detail) === null || _11 === void 0 ? void 0 : _11.payload) === null || _12 === void 0 ? void 0 : _12.control) === null || _13 === void 0 ? void 0 : _13.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) && ((_16 = (_15 = (_14 = event === null || event === void 0 ? void 0 : event.detail) === null || _14 === void 0 ? void 0 : _14.payload) === null || _15 === void 0 ? void 0 : _15.control) === null || _16 === void 0 ? void 0 : _16.endpoint)) {
        const response = await this.db.call(event.detail.payload.control.endpoint)(((_19 = (_18 = (_17 = event === null || event === void 0 ? void 0 : event.detail) === null || _17 === void 0 ? void 0 : _17.payload) === null || _18 === void 0 ? void 0 : _18.control) === null || _19 === void 0 ? void 0 : _19.params) || {});
        const results = response[((_22 = (_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.control) === null || _22 === void 0 ? void 0 : _22.resultsKey)
          ? event.detail.payload.control.resultsKey
          : (_25 = (_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.control) === null || _25 === void 0 ? void 0 : _25.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: !!((_27 = (_26 = event === null || event === void 0 ? void 0 : event.detail) === null || _26 === void 0 ? void 0 : _26.payload) === null || _27 === void 0 ? void 0 : _27.filter),
        filterEmptyText: ((_29 = (_28 = event === null || event === void 0 ? void 0 : event.detail) === null || _28 === void 0 ? void 0 : _28.payload) === null || _29 === void 0 ? void 0 : _29.filterEmptyText) || null,
        filterPlaceholderText: ((_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.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 ((_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.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: !!((_36 = (_35 = (_34 = event === null || event === void 0 ? void 0 : event.detail) === null || _34 === void 0 ? void 0 : _34.payload) === null || _35 === void 0 ? void 0 : _35.control) === null || _36 === void 0 ? void 0 : _36.multiple),
        data,
      });
      this.floatSelect.setVal((_39 = (_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.control) === null || _39 === void 0 ? void 0 : _39.value);
      this.floatSelect.open();
    }
    else if (triggerName === "login") {
      const type = ((_41 = (_40 = event === null || event === void 0 ? void 0 : event.detail) === null || _40 === void 0 ? void 0 : _40.payload) === null || _41 === void 0 ? void 0 : _41.type) || "email";
      let res;
      if (type === "email") {
        res = await this.auth.withEmailLink((_43 = (_42 = event === null || event === void 0 ? void 0 : event.detail) === null || _42 === void 0 ? void 0 : _42.payload) === null || _43 === void 0 ? void 0 : _43.email, {
          url: (_44 = state === null || state === void 0 ? void 0 : state.config) === null || _44 === void 0 ? void 0 : _44.url,
          dynamicLinkDomain: (_45 = state === null || state === void 0 ? void 0 : state.config) === null || _45 === void 0 ? void 0 : _45.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", ((_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.token) || getParameter("token"))).data();
        res = await this.auth.withToken(tempToken.token);
      }
      else {
        res = await this.auth.withSocial(type);
      }
      if ((_48 = res === null || res === void 0 ? void 0 : res.user) === null || _48 === void 0 ? void 0 : _48.uid) {
        const routerEl = document.querySelector("ion-router");
        routerEl.push("dashboard");
      }
    }
    else if (triggerName === "subscribe") {
      this.db.watchDocument((_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.collection, (_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.id, typeof ((_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.callback) === "function"
        ? (_56 = (_55 = event === null || event === void 0 ? void 0 : event.detail) === null || _55 === void 0 ? void 0 : _55.payload) === null || _56 === void 0 ? void 0 : _56.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((_58 = (_57 = event === null || event === void 0 ? void 0 : event.detail) === null || _57 === void 0 ? void 0 : _57.payload) === null || _58 === void 0 ? void 0 : _58.collection, (_60 = (_59 = event === null || event === void 0 ? void 0 : event.detail) === null || _59 === void 0 ? void 0 : _59.payload) === null || _60 === void 0 ? void 0 : _60.id);
    }
    else if (triggerName === "set") {
      if (((_63 = (_62 = (_61 = event === null || event === void 0 ? void 0 : event.detail) === null || _61 === void 0 ? void 0 : _61.event) === null || _62 === void 0 ? void 0 : _62.detail) === null || _63 === void 0 ? void 0 : _63.type) === "feedType") {
        const value = ((_65 = (_64 = event.detail) === null || _64 === void 0 ? void 0 : _64.payload) === null || _65 === void 0 ? void 0 : _65.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][(_67 = (_66 = event === null || event === void 0 ? void 0 : event.detail) === null || _66 === void 0 ? void 0 : _66.payload) === null || _67 === void 0 ? void 0 : _67.name] =
        (_69 = (_68 = event === null || event === void 0 ? void 0 : event.detail) === null || _68 === void 0 ? void 0 : _68.payload) === null || _69 === void 0 ? void 0 : _69.value;
      state.filters = { ...state.filters };
      console.log(state.filters);
    }
    else if (triggerName === "select") {
      if (((_71 = (_70 = event === null || event === void 0 ? void 0 : event.detail) === null || _70 === void 0 ? void 0 : _70.payload) === null || _71 === void 0 ? void 0 : _71.name) === "status") {
        await editJob(this.db, (_73 = (_72 = event === null || event === void 0 ? void 0 : event.detail) === null || _72 === void 0 ? void 0 : _72.el) === null || _73 === void 0 ? void 0 : _73.jobId, {
          status: (_75 = (_74 = event === null || event === void 0 ? void 0 : event.detail) === null || _74 === void 0 ? void 0 : _74.payload) === null || _75 === void 0 ? void 0 : _75.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 getMaterials() {
    try {
      state.materials = await listMaterials(this.db);
      console.log(state === null || state === void 0 ? void 0 : state.materials, "state materials");
    }
    catch (e) {
      console.log("Error getting materials", e);
    }
    return state.materials;
  }
  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.getMaterials();
    this.auth.onAuthChanged(async (session) => {
      var _a, _b;
      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: "/flows", component: "app-flow-list" }), h("ion-route", { component: "app-flow", url: "/flows/:flowId", componentProps: { app: this.app, db: this.db } }), 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/:toolId", 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: "/materials/:materialId", component: "app-material" }), h("ion-route", { url: "/materials", component: "app-material-list" }), 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/:userId", component: "app-sign" }), 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/new/:campaignId", component: "app-job-new" }), h("ion-route", { url: "/jobs/ad/:campaignId", 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/:locationId", component: "app-job-new", componentProps: { agent: true } }), h("ion-route", { url: "/jobs/agent/:locationId/: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<any>",
          "references": {
            "FireEnjinTriggerInput": {
              "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
      }];
  }
}
