"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _react = _interopRequireWildcard(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _reactRouterDom = require("react-router-dom");

var _lodash = _interopRequireDefault(require("lodash"));

var _moment = _interopRequireDefault(require("moment"));

var _md = _interopRequireDefault(require("crypto-js/md5"));

var _querystring = _interopRequireDefault(require("querystring"));

var _templates = require("../../../templates");

var _pages = require("../../../pages");

var _AuthDataSource = require("./AuthDataSource");

var _Auth = _interopRequireWildcard(require("./Auth"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

var authenCallbackPath = "/authen-callback";
/**
 * Format url
 */

function trimUrl(url, basePath) {
  return _lodash.default.trimEnd(basePath, '/') + '/' + _lodash.default.trimStart(url, '/');
}
/**
 * Login Component 
 */


function LoginComponent(_ref) {
  var props = _extends({}, _ref);

  (0, _react.useEffect)(function () {
    if (props.location.pathname === authenCallbackPath) {
      var urlParams = new URLSearchParams(props.location.search);
      var authenCode = urlParams.get('code');
      var clientId = props.clientId,
          clientSecret = props.clientSecret,
          redirectUri = props.redirectUri;
      (0, _AuthDataSource.setAccessToken)({
        authenCode: authenCode,
        clientId: clientId,
        clientSecret: clientSecret,
        redirectUri: redirectUri
      });
      props.history.push(props.defaultRoute);
    }
  });

  var _handleLogin = function _handleLogin(e) {
    e.preventDefault();
    var authenUri = props.authenUri,
        clientId = props.clientId,
        clientSecret = props.clientSecret,
        redirectUri = props.redirectUri,
        responseType = props.responseType,
        stateTimestamp = props.stateTimestamp;
    var params = {
      client_id: clientId,
      client_secret: clientSecret,
      redirect_uri: redirectUri,
      response_type: responseType
    };
    window.location.href = "".concat(authenUri, "?").concat(_querystring.default.stringify(params), "&state=").concat((0, _md.default)(stateTimestamp));
  };

  return _react.default.createElement(_pages.LoginPage, _extends({}, props, {
    onClickLogin: _handleLogin
  }));
}
/**
 * Auth Wrapper 
 */


function AuthWrapper(_ref2) {
  var props = _extends({}, _ref2);

  var _useAuthContext = (0, _Auth.useAuthContext)(),
      authData = _useAuthContext.authData,
      onLogin = _useAuthContext.onLogin,
      onLogout = _useAuthContext.onLogout;

  var loggedIn = authData ? true : false;

  function _handleLogin() {
    var urlParams = new URLSearchParams(props.location.search);
    var authenCode = urlParams.get('code');
    var clientId = props.clientId,
        clientSecret = props.clientSecret,
        redirectUri = props.redirectUri;
    onLogin();
    (0, _AuthDataSource.setAccessToken)({
      authenCode: authenCode,
      clientId: clientId,
      clientSecret: clientSecret,
      redirectUri: redirectUri
    });
    props.history.push(props.defaultRoute);
  }

  function _handleLogout() {
    onLogout();
    props.history.push(props.basePath);
  }

  return _react.default.createElement(_react.Fragment, null, props.render({
    authData: authData,
    loggedIn: loggedIn,
    onLogin: _handleLogin,
    onLogout: _handleLogout
  }));
}
/**
 * Main Component 
 */


function BackendSkeleton(_ref3) {
  var props = _extends({}, _ref3);

  (0, _react.useEffect)(function () {
    return function () {
      (0, _AuthDataSource.removeAccessToken)();
    };
  });

  var routes = _lodash.default.filter(props.config, function (value) {
    return value.title !== true && !value.children;
  });

  var routeConfig = props.config.filter(function (value) {
    return value.children;
  }).map(function (value) {
    return value.children;
  }).concat(routes).flat().map(function (value) {
    return _objectSpread({}, value, {
      path: trimUrl(value.path, props.basePath),
      component: value.component
    });
  });
  var navConfig = {
    items: _lodash.default.map(props.config, function (value) {
      return _objectSpread({}, value, {
        url: !value.children && trimUrl(value.path, props.basePath),
        children: value.children && value.children.map(function (child) {
          return _objectSpread({}, child, {
            url: trimUrl(child.path, props.basePath)
          });
        })
      });
    })
  };

  var loading = function loading() {
    return _react.default.createElement("div", {
      className: "animated fadeIn pt-1 text-center"
    }, "Loading...");
  };

  var parentProps = props;
  return _react.default.createElement(_reactRouterDom.BrowserRouter, null, _react.default.createElement(_react.Suspense, {
    fallback: loading()
  }, _react.default.createElement(_reactRouterDom.Switch, null, _react.default.createElement(_reactRouterDom.Route, {
    exact: true,
    name: "Login",
    path: props.loginPath,
    render: function render(props) {
      return _react.default.createElement(LoginComponent, _extends({}, props, parentProps));
    }
  }), _react.default.createElement(_reactRouterDom.Route, {
    name: "Login Callback",
    path: authenCallbackPath,
    render: function render(props) {
      return _react.default.createElement(LoginComponent, _extends({}, parentProps, props));
    }
  }), _react.default.createElement(_reactRouterDom.Route, {
    name: "Backend",
    path: props.basePath,
    render: function render(props) {
      return _react.default.createElement(_templates.BackendTemplate, _extends({
        routeConfig: routeConfig,
        navConfig: navConfig
      }, parentProps, props));
      /*return (
        <AuthProvider>
          <AuthWrapper {...props}>
            {
              (authData, loggedIn, onLogin, onLogout) => {
                console.log('is logged in = ', loggedIn)
                return (
                  <BackendTemplate
                    routeConfig={routeConfig}
                    navConfig={navConfig}
                    {...parentProps}
                    {...props}
                  />
                )
              }
            }
          </AuthWrapper>
        </AuthProvider>
      )*/
    }
  }), _react.default.createElement(_reactRouterDom.Route, {
    path: "*",
    component: _pages.Page404
  }))));
}

var _default = BackendSkeleton;
exports.default = _default;

var RouteWithLayout = function RouteWithLayout(_ref4) {
  var Component = _ref4.component,
      Layout = _ref4.layout,
      rest = _objectWithoutProperties(_ref4, ["component", "layout"]);

  return _react.default.createElement(_reactRouterDom.Route, _extends({}, rest, {
    render: function render(props) {
      return _react.default.createElement(Layout, null, _react.default.createElement(Component, null));
    }
  }));
};

BackendSkeleton.propTypes = {
  basePath: _propTypes.default.string,
  config: _propTypes.default.array.isRequired,
  clientId: _propTypes.default.string.isRequired,
  clientSecret: _propTypes.default.string.isRequired,
  authenUri: _propTypes.default.string.isRequired,
  redirectUri: _propTypes.default.string.isRequired,
  responseType: _propTypes.default.string.isRequired,
  stateTimestamp: _propTypes.default.number.isRequired,
  defaultRoute: _propTypes.default.string.isRequired
};
BackendSkeleton.defaultProps = {
  basePath: '/',
  loginPath: '/',
  authenUri: "https://oauth2.eng.psu.ac.th/authorize",
  redirectUri: window.location.origin + authenCallbackPath,
  responseType: "code",
  stateTimestamp: (0, _moment.default)().unix(),
  defaultRoute: "/dashboard"
};