"use strict";

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

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

var _modularityFront = _interopRequireDefault(require("modularity-front"));

var _reactMaterialize = require("react-materialize");

var _Button = _interopRequireDefault(require("@material-ui/core/Button"));

var _Form = _interopRequireDefault(require("../Modules/Form.js"));

var _UserService = _interopRequireDefault(require("../Services/UserService.js"));

var _DictionaryService = _interopRequireDefault(require("../Services/DictionaryService.js"));

var _Toast = _interopRequireDefault(require("../helpers/Toast"));

require("./UserPackage.css");

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

function _typeof(obj) { 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); }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }

function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

var Module = _modularityFront.default.Module;

var UserPackage =
/*#__PURE__*/
function (_Modularity$Module) {
  _inherits(UserPackage, _Modularity$Module);

  function UserPackage(props) {
    var _this;

    _classCallCheck(this, UserPackage);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(UserPackage).call(this, props));
    _this.state = {
      registerForm: false
    };
    var propertiesService = {
      Token: function Token(t) {
        _this.checkToken();

        _this.Token.set(t);

        _this.forceUpdate();
      },
      User: function User(u) {
        _this.User.set(u);

        _this.forceUpdate();
      }
    };
    _this.back_service = new _UserService.default(propertiesService); // this.Token.onUpdate((v) => { this.back_service.Token.update(v);this.forceUpdate(); });

    var withLogin = _this.LoginURL.value;

    if (withLogin) {
      _this.RoutingSystem.addRoute(withLogin, _this.RoutingSystem.currentView, 'PackageLogin');
    }

    var url = new URL(window.location.href);
    var confirmtoken = url.searchParams.get("token");

    if (confirmtoken) {
      _this.back_service.confirmUser(confirmtoken).then(function () {
        return _Toast.default.success("Ο χρήστης επιβεβαιώθηκε. Συνδέσου τώρα!");
      });
    }

    setTimeout(function () {
      return _this.checkToken();
    }, 0);

    _this.RoutingSystem.onRouteChange("Login", function () {
      return _this.checkToken();
    });

    return _this;
  }

  _createClass(UserPackage, [{
    key: "checkToken",
    value: function checkToken() {
      var withLogin = this.LoginURL.value;
      var route = this.RoutingSystem.getRoute().url;

      if (route === withLogin) {
        this.setState({
          login: true,
          ref: this.RoutingSystem.currentState.ref || "/home"
        });

        if (this.back_service.isLogged()) {
          this.CoreSystem.go(this.state.ref);
        }
      } else {
        this.setState({
          login: false
        });
      }
    }
  }, {
    key: "showLogin",
    value: function showLogin() {
      this.setState({
        login: true,
        ref: this.RoutingSystem.getRoute().url
      });
      this.CoreSystem.go("/login", {
        ref: this.RoutingSystem.getRoute().url
      });
    }
  }, {
    key: "login",
    value: function login(data) {
      var _this2 = this;

      // check if all data is comple
      if (!data) return;
      var username = data.username,
          password = data.password;
      if (username && password) this.back_service.login(data).then(function (d) {
        _Toast.default.notify(_DictionaryService.default.get("Welcome") + " &nbsp;<b>" + username + "</b>");

        _this2.CoreSystem.go(_this2.state.ref);
      }).catch(function (err) {
        if (err.status === 400) {
          _Toast.default.error(_DictionaryService.default.get("Wrong credentials"));
        } else if (err.status === 403) {
          _Toast.default.notify(_DictionaryService.default.get("A verification mail has been sent to your inbox. You need to verify before login."));
        }
      });
    }
  }, {
    key: "register",
    value: function register(data) {
      var _this3 = this;

      // check if all data is comple
      if (!data) return;
      var username = data.username,
          password = data.password,
          email = data.email;
      if (username && password && email) this.back_service.register(data).then(function (user) {
        _Toast.default.success(_DictionaryService.default.get("Successfully registered! Please login"));

        _this3.setState({
          registerForm: false
        });
      }).catch(function (err) {
        if (err.status === 400) {
          _Toast.default.error(_DictionaryService.default.get("Wrong credentials"));
        }
      });
    }
  }, {
    key: "logout",
    value: function logout() {
      var _this4 = this;

      this.back_service.logout().then(function () {
        _Toast.default.notify(_DictionaryService.default.get("Logged out")); //window.location.href = "/login";


        _this4.forceUpdate();
      }).catch(function () {
        _Toast.default.error("Cannot Logout");
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this5 = this;

      var Token = this.back_service.getToken() || 'missing';
      var User = this.back_service.User.value || {}; // console.log("Token : ", Token);

      var FormInputs = {
        "username": {
          type: "text",
          placeholder: "Username",
          columns: 12,
          filter: {
            required: true
          }
        },
        "password": {
          type: "password",
          placeholder: "Password",
          columns: 12,
          filter: {
            required: true,
            password: true
          }
        }
      };

      if (this.state.registerForm && this.withRegister.value) {
        FormInputs["email"] = {
          type: "email",
          placeholder: "Email",
          columns: 12,
          filter: {
            email: true,
            required: true
          }
        };
      }

      var LoginScreen = _react.default.createElement("div", {
        className: 'LoginScreen valign-wrapper'
      }, _react.default.createElement("div", {
        className: 'FormContainer hoverable'
      }, _react.default.createElement(_reactMaterialize.Row, null, _react.default.createElement(_reactMaterialize.Col, {
        s: 12
      }, _react.default.createElement("img", {
        src: this.Logo.value || ''
      })), _react.default.createElement(_reactMaterialize.Col, {
        s: 12,
        className: 'LoginText'
      }, _react.default.createElement("h4", null, this.Header.value || ''))), _react.default.createElement(_reactMaterialize.Row, null, _react.default.createElement(_reactMaterialize.Col, {
        s: 12
      }, _react.default.createElement(_Form.default, {
        key: Math.random(),
        className: 'center-align',
        FormInputs: FormInputs,
        button: this.state.registerForm ? _DictionaryService.default.get("Register") : _DictionaryService.default.get("Login"),
        onSubmit: function onSubmit(data) {
          return _this5.state.registerForm ? _this5.register(data) : _this5.login(data);
        },
        activeButton: true
      })), this.withRegister.value ? _react.default.createElement(_reactMaterialize.Col, {
        s: 12,
        className: 'RegisterText',
        onClick: function onClick() {
          return _this5.setState({
            registerForm: !_this5.state.registerForm
          });
        }
      }, this.state.registerForm ? _DictionaryService.default.get("Already registered? Login now!") : _DictionaryService.default.get("You don't have an account? Register here!")) : '')), _get(_getPrototypeOf(UserPackage.prototype), "render", this).call(this));

      var needsLogin = Token === "missing";
      return needsLogin ? this.state.login || this.ForceLogin.value ? LoginScreen : _react.default.createElement(_Button.default, {
        className: this.className.value,
        onClick: function onClick() {
          return _this5.showLogin();
        }
      }, _DictionaryService.default.get("Login")) : _react.default.createElement("div", null, _react.default.createElement(_Button.default, {
        className: this.className.value,
        onClick: function onClick() {
          return _this5.CoreSystem.go(_this5.UserURL.value);
        }
      }, User.username || '...'), _react.default.createElement(_Button.default, {
        className: this.className.value,
        onClick: function onClick() {
          return _this5.logout();
        }
      }, _DictionaryService.default.get("Logout")), _get(_getPrototypeOf(UserPackage.prototype), "render", this).call(this));
    }
  }]);

  return UserPackage;
}(_modularityFront.default.Module);

UserPackage.Inputs = {
  ForceLogin: {
    type: _modularityFront.default.Module.Types.Boolean,
    defaultValue: false
  },
  withRegister: {
    type: _modularityFront.default.Module.Types.Boolean,
    defaultValue: true
  },
  LoginURL: {
    type: _modularityFront.default.Module.Types.Text,
    defaultValue: '/login'
  },
  Logo: {
    type: _modularityFront.default.Module.Types.Text,
    defaultValue: '/logo.png'
  },
  Header: {
    type: _modularityFront.default.Module.Types.Text,
    defaultValue: 'Tonersales'
  },
  UserURL: {
    type: _modularityFront.default.Module.Types.Text,
    defaultValue: '/user'
  },
  className: {
    type: _modularityFront.default.Module.Types.Text
  }
};
UserPackage.Outputs = {
  Token: {},
  User: {}
};
UserPackage.Category = "NikatlasPackages";
UserPackage.EditPosition = "top-center";
var _default = UserPackage;
exports.default = _default;