import { injectNotifier } from '@dvn/alaca/global/notifier';
import { AppConfig } from '@dvn/core/models/app-config';
import { Membership } from '@dvn/core/models/membership';
import { getRouteParams } from '@dvn/core/util/route';
import { isUserLoggedIn } from '@dvn/kimlik/index';
import { Component, h, Host, Prop, State, Watch } from '@stencil/core';
import Tunnel from './context';
export class DvnAppContextInjector {
  constructor() {
    this.getLogger = () => this.logger.new('DvnAppContextInjector');
    this.getApp = (mid) => this.apiUye.getAppConfigOfMembership(mid).then(response => {
      this.appConfig = AppConfig.decode(response);
    });
  }
  onPathChange() {
    this.getLogger().debug('onPathChange');
    if (!isUserLoggedIn(this.storage, this.logger)) {
      this.getLogger().debug('onPathChange: skipping because the user is not logged in');
      // this injector is also used for anonymous routes
      return;
    }
    const { membershipId } = getRouteParams(this.path);
    const { membership } = this;
    const isNavigatedToMembershipForTheFirstTime = membershipId && !(membership === null || membership === void 0 ? void 0 : membership._id);
    const isSwitchedMembership = membershipId && (membership === null || membership === void 0 ? void 0 : membership._id) && membershipId !== (membership === null || membership === void 0 ? void 0 : membership._id);
    if (isNavigatedToMembershipForTheFirstTime) {
      this.logger.new('DvnAppContextInjector').debug('onPathChange', 'membership is selected for the first time');
      this.getSession();
    }
    else if (isSwitchedMembership) {
      this.logger.new('DvnAppContextInjector').debug('onPathChange', 'membership is changed');
      // app is changed from the left menu, load the new membership app
      this.appConfig = undefined;
      this.membership = undefined;
      this.getAppForMembership(membershipId);
    }
  }
  invalidateAppContext() {
    this.logger.new('DvnAppContextInjector').debug('invalidateAppContext');
    this.appConfig = undefined;
    this.membership = undefined;
    this.getMemberships();
  }
  async componentDidLoad() {
    this.getLogger().debug('componentDidLoad');
    if (!isUserLoggedIn(this.storage, this.logger)) {
      this.getLogger().debug('componentDidLoad: not fetching session because the user is not logged in');
      // this injector is also used for anonymous routes
      return;
    }
    this.getSession();
  }
  async getSession() {
    this.getLogger().debug('getSession');
    const session = await this.apiKimlik.getSession().catch((e) => {
      // this.error = e;
      console.log('getting session failed', e);
    }); //.finally(() => this.isProgressing = false);
    if (!session)
      return;
    this.user = session.user;
    this.userSettings = session.settings;
    const response = await this.apiUye.getMembershipsOfUser(this.user._id);
    const memberships = response.results;
    this.memberships = memberships;
    if (!memberships || memberships.length === 0) {
      this.getLogger().warn('getSession: user has no membership');
      return;
    }
    this.getMemberships();
  }
  async getMemberships() {
    const response = await this.apiUye.getMembershipsOfUser(this.user._id);
    const memberships = response.results;
    this.memberships = memberships;
    if (!memberships || memberships.length === 0) {
      return;
    }
    const { membershipId } = getRouteParams(this.path);
    this.getAppForMembership(membershipId);
  }
  async getAppForMembership(membershipId) {
    this.getLogger().debugGroup('getAppForMembership', { membershipId });
    if (membershipId) {
      this.membership = this.memberships.find(m => m._id === membershipId);
      if (this.membership) {
        this.getLogger().debugGroup('getAppForMembership: finding membership within existing memberships', { membershipId, membership: this.membership, memberships: this.memberships });
        this.getApp(this.membership.config._id);
        return;
      }
      else {
        // the membership in the route params doesn't belong to the user
        this.appConfig = AppConfig.decode({ mainNavigation: { items: [] }, mainContent: { centered: true } });
        return;
      }
    }
    this.membership = Membership.decode(this.memberships[0]);
    this.getLogger().debugGroup('getAppForMembership: using first membership in existing memberships', {
      membershipId,
      membership: this.membership,
      memberships: this.memberships
    });
    this.getApp(this.memberships[0].config._id);
  }
  render() {
    return (h(Host, null,
      h(Tunnel.Provider, { state: {
          apiAtama: this.apiAtama,
          apiData: this.apiData,
          apiKimlik: this.apiKimlik,
          apiTakvim: this.apiTakvim,
          apiUye: this.apiUye,
          apiSozluk: this.apiSozluk,
          logger: this.logger,
          storage: this.storage,
          appContextInvalidator: () => this.invalidateAppContext(),
          appConfig: this.appConfig,
          membership: this.membership,
          memberships: this.memberships,
          notifier: this.notifier,
          user: this.user,
          userSettings: this.userSettings,
          theme: this.theme,
        } },
        h("slot", null))));
  }
  static get is() { return "dvn-app-context-injector"; }
  static get properties() { return {
    "apiAtama": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "AtamaApi",
        "resolved": "AtamaApi",
        "references": {
          "AtamaApi": {
            "location": "import",
            "path": "../../../../atama/src/api/atamaApi"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "apiData": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "DataApi",
        "resolved": "DataApi",
        "references": {
          "DataApi": {
            "location": "import",
            "path": "@dvn/core/api"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "apiKimlik": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "KimlikApi",
        "resolved": "KimlikApi",
        "references": {
          "KimlikApi": {
            "location": "import",
            "path": "@dvn/kimlik/api/kimlik-api"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "apiTakvim": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "TakvimApi",
        "resolved": "TakvimApi",
        "references": {
          "TakvimApi": {
            "location": "import",
            "path": "@dvn/takvim/api/takvimApi"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "apiUye": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "UyeApi",
        "resolved": "UyeApi",
        "references": {
          "UyeApi": {
            "location": "import",
            "path": "@dvn/uye/api"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "apiSozluk": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "SozlukApi",
        "resolved": "SozlukApi",
        "references": {
          "SozlukApi": {
            "location": "import",
            "path": "@dvn/sozluk/api"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "logger": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "Logger",
        "resolved": "Logger",
        "references": {
          "Logger": {
            "location": "import",
            "path": "@dvn/core/log/logger"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "storage": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "Storage",
        "resolved": "Storage",
        "references": {
          "Storage": {
            "location": "import",
            "path": "@dvn/kimlik/storage/Storage.interface"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "path": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "path",
      "reflect": false
    },
    "notifier": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "Notifier",
        "resolved": "Notifier",
        "references": {
          "Notifier": {
            "location": "import",
            "path": "@dvn/alaca/global/notifier/models"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "theme": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "AlacaTheme",
        "resolved": "AlacaTheme",
        "references": {
          "AlacaTheme": {
            "location": "import",
            "path": "@dvn/alaca/theme"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    }
  }; }
  static get states() { return {
    "appConfig": {},
    "membership": {},
    "memberships": {},
    "user": {},
    "userSettings": {}
  }; }
  static get watchers() { return [{
      "propName": "path",
      "methodName": "onPathChange"
    }]; }
}
injectNotifier(DvnAppContextInjector);
