import { c as getAssetPath, h } from './index-c04b9ed5.js';
import { s as set, r as remove, g as get } from './localstorage.service-4bf408c8.js';
import { H as HttpService } from './httpService-7b75b095.js';
import { A as AuthStore } from './auth.store-dba2c2da.js';

//import * as abpTypings from '../lib/abp';
class Utils {
  constructor() {
    this.sample = (array) => array[Math.floor(Math.random() * array.length)];
    this.keyBy = (array, keyMap, valMap) => array.reduce((obj, item) => {
      obj[keyMap(item)] = valMap ? valMap(item) : item;
      return obj;
    }, {});
    this.debounce = (fn, wait) => {
      let scheduled = null;
      return (...args) => {
        clearTimeout(scheduled);
        scheduled = setTimeout(fn, wait, ...args);
      };
    };
  }
  loadScript(url) {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;
    document.body.appendChild(script);
  }
  loadScriptAsync(src) {
    return new Promise(function (resolve, reject) {
      const s = document.createElement('script');
      let r = false;
      s.type = 'text/javascript';
      s.src = src;
      s.async = true;
      s.onerror = function (err) {
        reject(err);
      };
      s.onload = s.onreadystatechange = function () {
        // console.log(this.readyState); // uncomment this line to see which ready states are called.
        if (!r && (!this.readyState || this.readyState == 'complete')) {
          r = true;
          resolve(true);
        }
      };
      const t = document.getElementsByTagName('script')[0];
      t.parentElement.insertBefore(s, t);
    });
  }
  extend(...args) {
    let options, name, src, srcType, copy, copyIsArray, clone, target = args[0] || {}, i = 1, length = args.length, deep = false;
    if (typeof target === 'boolean') {
      deep = target;
      target = args[i] || {};
      i++;
    }
    if (typeof target !== 'object' && typeof target !== 'function') {
      target = {};
    }
    if (i === length) {
      target = this;
      i--;
    }
    for (; i < length; i++) {
      if ((options = args[i]) !== null) {
        for (name in options) {
          src = target[name];
          copy = options[name];
          if (target === copy) {
            continue;
          }
          srcType = Array.isArray(src) ? 'array' : typeof src;
          if (deep && copy && ((copyIsArray = Array.isArray(copy)) || typeof copy === 'object')) {
            if (copyIsArray) {
              copyIsArray = false;
              clone = src && srcType === 'array' ? src : [];
            }
            else {
              clone = src && srcType === 'object' ? src : {};
            }
            target[name] = this.extend(deep, clone, copy);
          }
          else if (copy !== undefined) {
            target[name] = copy;
          }
        }
      }
    }
    return target;
  }
  setLocalization() {
    if (!sparkle.utils.getCookieValue('Sparkle.Localization.CultureName')) {
      let language = navigator.language;
      sparkle.utils.setCookieValue('Sparkle.Localization.CultureName', language, new Date(new Date().getTime() + 5 * 365 * 86400000), sparkle.appPath);
    }
  }
}
const Util = new Utils();

//declare var sparkle: any;
async function setupConfig(config) {
  if (!window) {
    return;
  }
  const win = window;
  const Sparkle = win.Sparkle;
  if (Sparkle && Sparkle.config && Sparkle.config.constructor.name !== 'Object') {
    console.error('Sparkle config was already initialized');
    return;
  }
  win.Sparkle = win.Sparkle || {};
  win.Sparkle.config = Object.assign(Object.assign({}, win.Sparkle.config), config);
  // sparkle.config = {
  //   ...config.sparkle
  // };
  return win.Sparkle.config;
}
async function initSetupConfig(config) {
  await Util.loadScriptAsync(getAssetPath(`../assets/lib/sparkle.js`));
  await setupConfig(config);
}

const AppConsts = {
  AUTH_USER_LOCALSTORAGE: "CurrentUser",
  userManagement: {
    defaultAdminUserName: 'admin',
  },
  localization: {
    defaultLocalizationSourceName: 'Test',
  },
  authorization: {
    encrptedAuthTokenName: 'enc_auth_token',
  }
};

class AuthService {
  constructor() { }
  static getInstance() {
    if (!AuthService.instance) {
      AuthService.instance = new AuthService();
    }
    return AuthService.instance;
  }
  async authenticate(authenticationInput) {
    const headers = {
      'Content-Type': 'application/json',
    };
    AuthStore.state.loading = true;
    let result;
    try {
      result = await HttpService.http.post('api/Account/Authenticate', authenticationInput, {
        headers: headers
      });
      if (result) {
        const authData = result.Data;
        const authUser = {
          Id: authData.Id,
          UserName: authData.UserName,
          Email: authData.Email,
          Roles: authData.Roles,
          IsVerified: authData.IsVerified,
          JWToken: authData.JWToken,
          IssuedOn: authData.IssuedOn,
          ExpiresOn: authData.ExpiresOn,
          RefreshToken: authData.RefreshToken,
          PhotoUrl: "",
          IsFacilitator: authData.Roles.indexOf("Facilitator") > 0
        };
        const expireDate = authenticationInput.RememberClient ? new Date(authUser.ExpiresOn) : undefined;
        sparkle.auth.setToken(authUser.JWToken, expireDate);
        //TODO: change authUser.JWToken to encrypted
        sparkle.utils.setCookieValue(AppConsts.authorization.encrptedAuthTokenName, authUser.JWToken, expireDate, sparkle.appPath);
        await set(AppConsts.AUTH_USER_LOCALSTORAGE, authUser);
        AuthStore.state.authUser = Object.assign({}, authUser);
        AuthStore.state.loading = false;
        return authUser;
      }
    }
    catch (e) {
      AuthStore.state.loading = false;
      return e;
    }
  }
  async signOut() {
    await remove(AppConsts.AUTH_USER_LOCALSTORAGE);
    sessionStorage.clear();
    sparkle.auth.clearToken();
    AuthStore.state.authUser = null;
    AuthStore.state.isAuthenticated = false;
  }
  async getLocalAuthUser() {
    return get(AppConsts.AUTH_USER_LOCALSTORAGE);
  }
}

function isGranted(permissionName) {
  return sparkle.auth.isGranted(permissionName);
}

var __rest = (undefined && undefined.__rest) || function (s, e) {
  var t = {};
  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
    t[p] = s[p];
  if (s != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
      if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
        t[p[i]] = s[p[i]];
    }
  return t;
};
const Route = (_a) => {
  var { component, permission, render } = _a, props = __rest(_a, ["component", "permission", "render"]);
  const Component = component;
  return (h("stencil-route", Object.assign({}, props, { routeRender: (props) => {
      if (!AuthStore.state.isAuthenticated)
        return (h("stencil-router-redirect", { url: "/login" }));
      if (permission && !isGranted(permission)) {
        return (h("stencil-router-redirect", { url: "/unauthorized" }));
      }
      return Component ? h(Component, Object.assign({}, props, props.componentProps)) : render(props);
    } })));
};
const PrivateRoute = Route;

export { AuthService as A, PrivateRoute as P, initSetupConfig as i, setupConfig as s };
