import { injectNotifier } from '@dvn/alaca/global/notifier';
import { DataApiImpl } from '@dvn/core/api/dataApi';
import { Logger } from '@dvn/core/log/logger';
import { AppConfig } from '@dvn/core/models/app-config';
import { Membership } from '@dvn/core/models/membership';
import { getRouteParams } from '@dvn/core/util/route';
import { getSessionData, isUserLoggedIn } from '@dvn/kimlik/index';
import { CookieStorage } from '@dvn/kimlik/storage/cookie';
import { SozlukApi } from '@dvn/sozluk/api';
import { Component, h, Host, Prop, State } from '@stencil/core';
import Tunnel from '../../../../core/src/global/context/context';
import { KimlikApiMentornity } from '../../api/kimlik';
import { UyeApiMentornity } from '../../api/uye';
import { dataApiEndpoint, mentornityApiEndpoint } from '../../constants/env';
export class MentornityConsoleAppContextInjector {
  componentWillLoad() {
    const defaultHeaders = {
      'Session-Token': 'NTdiMzY3NjBlNjNiY2UxZWViMDAwMDA0',
    };
    if (getSessionData().token) {
      defaultHeaders['Authorization'] = `Bearer ${getSessionData().token}`;
    }
    this.storage = new CookieStorage();
    this.logger = new Logger('MentornityConsoleAppContextInjector').setLevel('debug');
    this.logger.infoGroup('componentWillLoad');
    // this.apiAtama = new AtamaApiImpl('', defaultHeaders);
    this.apiData = new DataApiImpl(dataApiEndpoint, {
      Authorization: defaultHeaders['Authorization'],
    });
    this.apiKimlik = new KimlikApiMentornity(mentornityApiEndpoint, defaultHeaders);
    this.apiUye = new UyeApiMentornity(mentornityApiEndpoint, defaultHeaders);
    this.apiSozluk = new SozlukApi();
  }
  componentDidLoad() {
    if (!isUserLoggedIn()) {
      // this injector is also used for anonymous routes
      return;
    }
    const { membershipId } = getRouteParams(location.pathname);
    const getApp = (mid) => this.apiUye.getAppConfigOfMembership(mid).then(response => {
      this.appConfig = AppConfig.decode(response);
    });
    this.apiKimlik.getSession().then(response => {
      this.user = response.user;
      this.apiUye.getMembershipsOfUser(response.user._id).then(response => {
        const memberships = response.results;
        this.memberships = memberships;
        if (!memberships || memberships.length === 0) {
          return;
        }
        if (membershipId) {
          this.membership = memberships.find(m => m._id === membershipId);
          getApp(this.membership.config._id);
          return;
        }
        this.membership = Membership.decode(memberships[0]);
        getApp(memberships[0].config._id);
      });
    });
  }
  invalidateAppContext() {
    this.logger.debug('invalidateAppContext');
  }
  render() {
    return (h(Host, null,
      h(Tunnel.Provider, { state: {
          apiAtama: this.apiAtama,
          apiData: this.apiData,
          apiKimlik: this.apiKimlik,
          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,
          theme: this.theme,
        } },
        h("slot", null))));
  }
  static get is() { return "mentornity-console-app-context-injector"; }
  static get properties() { return {
    "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": {}
  }; }
}
injectNotifier(MentornityConsoleAppContextInjector);
