import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import React, { useState, useEffect, createContext, useContext, useMemo, useReducer } from "react";
import { useAppConfig } from "../../components/AppConfig";
import CognitoHandler from "./cognito-handler.js";
export var authProviders = ["cognito"];
var AuthContext = createContext({
  authProvider: "none"
});
export var AuthProvider = function AuthProvider(_ref) {
  var children = _ref.children;

  var _useAppConfig = useAppConfig(),
      appConfig = _useAppConfig.appConfig,
      fromConfig = _useAppConfig.fromConfig;

  var _useState = useState({
    authProvider: "none"
  }),
      _useState2 = _slicedToArray(_useState, 2),
      handler = _useState2[0],
      setHandler = _useState2[1];

  var authProvider = fromConfig("auth.provider");

  var _useReducer = useReducer(function (state) {
    return state + 1;
  }, 0),
      _useReducer2 = _slicedToArray(_useReducer, 2),
      handlerVersion = _useReducer2[0],
      incHandlerVersion = _useReducer2[1];

  var _useReducer3 = useReducer(function (state) {
    return state + 1;
  }, 0),
      _useReducer4 = _slicedToArray(_useReducer3, 2),
      handlerErrorVersion = _useReducer4[0],
      incHandlerErrorVersion = _useReducer4[1];

  useEffect(function () {
    if (handler && handler.authProvider === authProvider) return;

    if (authProvider === "cognito") {
      setHandler(new CognitoHandler(appConfig));
    }
  }, [authProvider, appConfig, handler]);
  useEffect(function () {
    if (!handler) return;
    var interval = setInterval(function () {
      if (handler.hasChanged) {
        incHandlerVersion();
        handler.hasChanged = false;
      }

      if (handler.errorOccured) {
        incHandlerErrorVersion();
        handler.errorOccured = false;
      }
    }, 100);
    return function () {
      clearInterval(interval);
    };
  }, [handler, handlerVersion, handlerErrorVersion]);
  var contextValue = useMemo(function () {
    return _objectSpread(_objectSpread({
      authProvider: handler.authProvider
    }, handler.getState ? handler.getState() : {}), {}, {
      // TODO remove setUser
      setUser: handler.setUser,
      logout: handler.logout,
      login: handler.login,
      completeSignUp: handler.completeSignUp,
      passwordValidator: handler.passwordValidator,
      handlerVersion: handlerVersion,
      handlerErrorVersion: handlerErrorVersion
    });
  }, [handler, handlerVersion, handlerErrorVersion]);
  return /*#__PURE__*/React.createElement(AuthContext.Provider, {
    value: contextValue
  }, children);
};
export var useAuth = function useAuth() {
  return useContext(AuthContext);
};
export default useAuth;