import {
  StorageService
} from "./chunk-M3LFBN7N.js";
import {
  generateId
} from "./chunk-N36JE2BE.js";
import {
  BehaviorSubject,
  HttpClient,
  Injectable,
  Location,
  Observable,
  Subject,
  setClassMetadata,
  tap,
  ɵɵdefineInjectable,
  ɵɵinject
} from "./chunk-VAMMRICA.js";
import {
  __async
} from "./chunk-RVA4KI76.js";

// src/app/shared/navigation/services/device-route.service.ts
var _DeviceRouteService = class _DeviceRouteService {
  constructor(location) {
    this.location = location;
    this.transitionInMs = 250;
    this.routes = {};
    this.activeRoute = new BehaviorSubject(void 0);
    this.isPWA = window.matchMedia("(display-mode: standalone)").matches;
  }
  setTransition(ms) {
    this.transitionInMs = ms;
  }
  // #endregion
  // #region Params
  routeParams(type) {
    const route = this.routes[type];
    if (route != null) {
      return route.params;
    }
    return new BehaviorSubject([]);
  }
  closeAllRoutes(excludeType) {
    for (const key in this.routes) {
      if (this.routes.hasOwnProperty(key)) {
        const route = this.routes[key];
        if (route.type != excludeType) {
          this.closeRoute(route.type);
        }
      }
    }
  }
  closeRoute(type, transitionInMs = this.transitionInMs) {
    const route = this.routes[type];
    if (route != null) {
      route.closing = true;
      setTimeout(() => {
        route.active = false;
        route.closing = false;
        route.animating = false;
      }, transitionInMs);
    }
  }
  verifyRoute(route) {
    return new Promise((res, rej) => {
      if (route.requireAuthentication) {
        const userAuthenticated = true;
        if (userAuthenticated) {
          res(true);
        } else {
          res(false);
        }
      } else {
        res(true);
      }
    });
  }
  setBrowserPath(type, params) {
    if (!this.isPWA) {
      const route = this.routes[type];
      if (route != null) {
        if (route.path == ":base") {
          const fullPath = `${params.join("/")}`;
          this.location.go(fullPath);
        } else {
          const fullPath = `${route.path}/${params.join("/")}`;
          this.location.go(fullPath);
        }
      }
    }
  }
  viewRouteByType(type, params = [], animate = true) {
    const route = this.routes[type];
    if (route != null) {
      if (route.active) {
        route.params.next(params);
      } else {
        this.verifyRoute(route).then((canLoadRoute) => {
          if (canLoadRoute) {
            this.closeAllRoutes(type);
            this.viewRoute(route, params, animate);
          } else {
          }
        });
      }
    }
  }
  viewRoute(route, params = [], animate = true) {
    this.verifyRoute(route).then((canLoadRoute) => {
      if (canLoadRoute) {
        route.params.next(params);
        route.active = true;
        route.animating = animate;
        this.setBrowserPath(route.type, params);
        this.activeRoute.next(route);
        setTimeout(() => {
          route.animating = false;
        }, this.transitionInMs);
      }
    });
  }
  resetParams(type, params) {
    const route = this.routes[type];
    if (route != null) {
      route.params.next(params);
      this.setBrowserPath(type, params);
    }
  }
  watchLocationChange() {
    this.locationSubscription = this.location.subscribe((e) => {
      if (e.pop) {
        console.log(e.url);
      }
    });
  }
  watchForLogin() {
  }
  monitorAuthentication() {
  }
  checkRoute(route, animate = true) {
    const matchingRoute = this.findMatchingRoute(route);
    if (matchingRoute != null) {
      this.viewRoute(matchingRoute, matchingRoute.params.getValue(), animate);
    }
  }
  findMatchingRoute(url) {
    url = url.toLocaleLowerCase();
    if (url.indexOf("code") > -1) {
      const authRoute = this.routes["Authentication"];
      if (authRoute != null) {
        return authRoute;
      }
    }
    let matchingRoute;
    for (const key in this.routes) {
      const route = this.routes[key];
      if (url == route.path || url.indexOf(route.path) == 0 && url.lastIndexOf("/") != 0) {
        matchingRoute = route;
        break;
      }
    }
    if (matchingRoute != null) {
      const basePath = matchingRoute.path;
      const paramString = url.slice(basePath.length);
      const params = paramString.split("/");
      if (params[0].length <= 0) {
        params.splice(0, 1);
      }
      matchingRoute.params.next(params);
      return matchingRoute;
    } else {
      return this.defaultRoute;
    }
  }
  init(routes, defaultRoute, transitionInMs = 250) {
    this.routes = routes;
    this.defaultRoute = defaultRoute;
    this.transitionInMs = transitionInMs;
    this.watchLocationChange();
    this.monitorAuthentication();
    this.checkRoute(window.location.pathname, false);
  }
  // #endregion
  ngOnDestroy() {
    this.authSubscription?.unsubscribe();
    this.locationSubscription?.unsubscribe();
    this.authSubscription?.unsubscribe();
  }
};
_DeviceRouteService.\u0275fac = function DeviceRouteService_Factory(__ngFactoryType__) {
  return new (__ngFactoryType__ || _DeviceRouteService)(\u0275\u0275inject(Location));
};
_DeviceRouteService.\u0275prov = /* @__PURE__ */ \u0275\u0275defineInjectable({ token: _DeviceRouteService, factory: _DeviceRouteService.\u0275fac, providedIn: "root" });
var DeviceRouteService = _DeviceRouteService;
(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(DeviceRouteService, [{
    type: Injectable,
    args: [{
      providedIn: "root"
    }]
  }], () => [{ type: Location }], null);
})();

// src/app/shared/reminders/models/reminder.ts
var Reminder = class {
  constructor(creator, recipient) {
    this.id = "";
    this.title = "";
    this.note = "";
    this.events = [];
    this.status = ReminderStatus.Created;
    this.priority = ReminderPriority.Standard;
    this.scheduled_Utc = /* @__PURE__ */ new Date();
    this.created_Utc = /* @__PURE__ */ new Date();
    this.lastUpdated_Utc = /* @__PURE__ */ new Date();
    this.completing = false;
    this.creator = creator;
    this.recipient = recipient;
  }
};
var ReminderReferenceType;
(function(ReminderReferenceType2) {
  ReminderReferenceType2["General"] = "General";
  ReminderReferenceType2["Appointment"] = "Appointment";
})(ReminderReferenceType || (ReminderReferenceType = {}));
var ReminderStatus;
(function(ReminderStatus2) {
  ReminderStatus2["Created"] = "Created";
  ReminderStatus2["Completed"] = "Completed";
})(ReminderStatus || (ReminderStatus = {}));
var ReminderPriority;
(function(ReminderPriority2) {
  ReminderPriority2["Standard"] = "Standard";
  ReminderPriority2["Critical"] = "Critical";
})(ReminderPriority || (ReminderPriority = {}));
var ReminderEventType;
(function(ReminderEventType2) {
  ReminderEventType2["Created"] = "Created";
  ReminderEventType2["Completed"] = "Completed";
  ReminderEventType2["Changed"] = "Changed";
})(ReminderEventType || (ReminderEventType = {}));

// src/app/shared/reminders/services/reminder.service.ts
var _ReminderService = class _ReminderService {
  constructor(http, storageService) {
    this.http = http;
    this.storageService = storageService;
    this.managingReminder = false;
    this.reminderSaved = new Subject();
  }
  manageReminder(reminder, creator, recipient) {
    this.reminderToManage = reminder;
    if (reminder != null) {
      this.reminderToManage = reminder;
    } else {
      this.reminderToManage = new Reminder(creator, recipient);
    }
    this.managingReminder = true;
  }
  stopManagingReminder() {
    window.clearTimeout(this.managingReminderTimer);
    this.managingReminder = false;
    this.reminderSaved.next();
    this.managingReminderTimer = window.setTimeout(() => {
      this.reminderToManage = void 0;
    }, 250);
  }
  // #endregion
  // #region Reminders
  getLastRemindersRetrieval(userId) {
    const lastRetrieval = localStorage.getItem(`u_${userId}_rr`);
    if (lastRetrieval != null) {
      try {
        return parseInt(lastRetrieval);
      } catch {
        return void 0;
      }
    }
    return void 0;
  }
  updateLastRemindersRetrieval(userId) {
    const now = /* @__PURE__ */ new Date();
    localStorage.setItem(`u_${userId}_rr`, `${now.getTime()}`);
  }
  syncRemindersForUser(userId, forceAll = false) {
    let url = `{{api}}/reminders/latest`;
    if (!forceAll) {
      const lastRetrievalInMs = this.getLastRemindersRetrieval(userId);
      if (lastRetrievalInMs != null) {
        const now = /* @__PURE__ */ new Date();
        const sinceInMs = now.getTime() - lastRetrievalInMs;
        url = url + `/${sinceInMs}`;
      }
    }
    return this.http.get(url).pipe(tap((reminders) => __async(this, null, function* () {
      yield this.storageService.remoteStoreReminders(reminders);
      this.updateLastRemindersRetrieval(userId);
    })));
  }
  getReminders(userId) {
    return new Observable((o) => {
      this.storageService.getRemindersForUser(userId).then((reminders) => {
        o.next(reminders);
        o.complete();
      }).catch(() => {
        o.error();
        o.complete();
      });
    });
  }
  createReminder(creator, recipient, title, note, priority, scheduled_Utc, referenceId, referenceType) {
    let reference = void 0;
    if (referenceId != null && referenceType != null) {
      reference = {
        referenceId,
        type: referenceType,
        content: ""
      };
    }
    const reminder = {
      id: generateId(),
      creator,
      recipient,
      title,
      note,
      events: [],
      status: ReminderStatus.Created,
      priority,
      scheduled_Utc,
      created_Utc: /* @__PURE__ */ new Date(),
      lastUpdated_Utc: /* @__PURE__ */ new Date(),
      reference,
      completing: false
    };
    this.storeReminder(reminder);
  }
  storeReminder(reminder) {
    return __async(this, null, function* () {
      yield this.storageService.storeReminder(reminder);
    });
  }
};
_ReminderService.\u0275fac = function ReminderService_Factory(__ngFactoryType__) {
  return new (__ngFactoryType__ || _ReminderService)(\u0275\u0275inject(HttpClient), \u0275\u0275inject(StorageService));
};
_ReminderService.\u0275prov = /* @__PURE__ */ \u0275\u0275defineInjectable({ token: _ReminderService, factory: _ReminderService.\u0275fac, providedIn: "root" });
var ReminderService = _ReminderService;
(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && setClassMetadata(ReminderService, [{
    type: Injectable,
    args: [{
      providedIn: "root"
    }]
  }], () => [{ type: HttpClient }, { type: StorageService }], null);
})();

export {
  DeviceRouteService,
  ReminderReferenceType,
  ReminderStatus,
  ReminderPriority,
  ReminderService
};
//# sourceMappingURL=chunk-ZEKYPX2O.js.map
