"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");

require("./UserAccount.css");

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

var _AddressBox = _interopRequireDefault(require("../../Modules/AddressBox"));

var _ArraySelector = _interopRequireDefault(require("../../Modules/ArraySelector"));

var _AddressInput = _interopRequireDefault(require("../../Inputs/AddressInput"));

var _TableData = _interopRequireDefault(require("../../HigherModules/TableData"));

var _ClientInput = _interopRequireDefault(require("../../Inputs/ClientInput"));

var _Merge = _interopRequireDefault(require("../../helpers/Merge"));

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

var _AddressesDisplay = _interopRequireDefault(require("../../HigherModules/AddressesDisplay"));

var _Repository = _interopRequireDefault(require("../../Services/Repository"));

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

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

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; // let Link = Modularity.Modules.Link;

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

  function UserAccount(props) {
    var _this;

    _classCallCheck(this, UserAccount);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(UserAccount).call(this, props));
    _this.state = {
      view: "info" //this.getProfile();

    };
    _this.addressRepo = new _Repository.default('addresses', _this.Token.value);
    _this.accountRepo = new _Repository.default('accounts', _this.Token.value);
    _this.ordersRepo = new _Repository.default('orders', _this.Token.value, [{
      type: "descending",
      field: "createdAt"
    }]);
    _this.userService = new _UserService.default({});

    _this.Token.onUpdate(function () {
      return _this.handleToken();
    });

    _this.handleToken();

    _this.RoutingSystem.onRouteChange("UserAccount", function () {
      _this.checkRoute();
    });

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

  _createClass(UserAccount, [{
    key: "checkRoute",
    value: function checkRoute() {
      var route = this.RoutingSystem.getRoute().url || '';

      if (route.endsWith("/orders")) {
        this.setState({
          view: "orders"
        });
      } else if (route.endsWith("/addresses")) {
        this.setState({
          view: "addresses"
        });
      } else {
        this.setState({
          view: "info"
        });
      }
    }
  }, {
    key: "updateUser",
    value: function updateUser() {
      var _this2 = this;

      this.userService.getUser(this.Token.value).then(function (user) {
        return _this2.setState({
          user: user
        });
      });
    }
  }, {
    key: "handleToken",
    value: function handleToken() {
      if (this.Token.value === undefined) return;

      if (this.Token.value === "missing" && this.RoutingSystem.getRoute().url !== "/login" && this.routeMatch()) {
        this.CoreSystem.go('/login', {
          ref: this.RoutingSystem.getRoute().url
        }, true);
      }

      this.accountRepo.setToken(this.Token.value);
      this.addressRepo.setToken(this.Token.value);
      this.ordersRepo.setToken(this.Token.value);
      this.updateUser();
      this.forceUpdate();
    }
  }, {
    key: "routeMatch",
    value: function routeMatch() {
      return this.RoutingSystem.getRoute().url.startsWith(this.baseURL.value);
    }
  }, {
    key: "updateUserInfo",
    value: function updateUserInfo(data) {
      var _this3 = this;

      this.accountRepo.update(this.state.user.Account.id, data).then(function () {
        return _this3.updateUser();
      }).then(function () {
        return _Toast.default.notify(_DictionaryService.default.get("Successfully updated user info"));
      });
    }
  }, {
    key: "changePass",
    value: function changePass(data) {
      if (data.npass !== data.rpass) {
        _Toast.default.error("New Passwords are different");

        return;
      }

      this.userService.changePass(this.Token.value, data.cpass, data.npass).then(function () {
        return _Toast.default.notify("Password changed");
      }).catch(function () {
        return _Toast.default.error("Wrong credentials");
      });
    }
  }, {
    key: "_viewOrder",
    value: function _viewOrder(order) {
      console.log("sss", order.id);
      this.CoreSystem.go('/profile/order/' + order.id);
    }
  }, {
    key: "render",
    value: function render() {
      var _this4 = this;

      var Link = function Link(props) {
        return _react.default.createElement("div", {
          onClick: function onClick() {
            _this4.CoreSystem.go(props.link);
          }
        }, props.children);
      };

      return this.state.user ? _react.default.createElement("div", {
        className: "row UserAccount " + this.ClassName.value
      }, _react.default.createElement("div", {
        className: 'col s12 m4 l3 Menu '
      }, _react.default.createElement("div", {
        className: "Menu_container"
      }, _react.default.createElement("h6", {
        className: "Menu_header"
      }, _DictionaryService.default.get("User Profile")), _react.default.createElement(Link, {
        link: '/user/orders',
        className: this.state.view === "orders" && 'selected'
      }, _react.default.createElement("i", {
        className: "fa fa-shopping-basket"
      }), _react.default.createElement("span", null, _DictionaryService.default.get("Orders"))), _react.default.createElement(Link, {
        link: '/user',
        className: this.state.view === "info" && 'selected'
      }, _react.default.createElement("i", {
        className: "fa fa-user"
      }), _react.default.createElement("span", null, _DictionaryService.default.get("Account information"))), _react.default.createElement(Link, {
        link: '/user/addresses',
        className: this.state.view === "addresses" && 'selected'
      }, _react.default.createElement("i", {
        className: "fa fa-home"
      }), _react.default.createElement("span", null, _DictionaryService.default.get("Addresses"))))), _react.default.createElement("div", {
        className: 'col s12 m8 l9 wrapper'
      }, _react.default.createElement(_reactMaterialize.Card, {
        className: ""
      }, this.state.view === "orders" && _react.default.createElement(Orders, {
        service: this.ordersRepo,
        viewOrder: function viewOrder(e) {
          return _this4._viewOrder(e);
        }
      }), this.state.view === "info" && _react.default.createElement(Info, {
        account: this.state.user.Account,
        onSubmit: function onSubmit(data) {
          return _this4.updateUserInfo(data);
        },
        onChangePassSubmit: function onChangePassSubmit(data) {
          return _this4.changePass(data);
        }
      }), this.state.view === "addresses" && _react.default.createElement("div", null, _DictionaryService.default.get("My addresses"), _react.default.createElement("br", null), _react.default.createElement(_AddressesDisplay.default, {
        key: this.addressRepo.token,
        service: this.addressRepo
      })))), _get(_getPrototypeOf(UserAccount.prototype), "render", this).call(this)) : null;
    }
  }]);

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

var Orders =
/*#__PURE__*/
function (_React$Component) {
  _inherits(Orders, _React$Component);

  function Orders(props) {
    var _this5;

    _classCallCheck(this, Orders);

    _this5 = _possibleConstructorReturn(this, _getPrototypeOf(Orders).call(this, props));
    _this5.state = {};
    _this5.tableHeaders = {
      "Αριθμός παραγγελίας": "id",
      "Ημερομηνία παραγγελίας": {
        field: "createdAt",
        type: "date"
      },
      "Κατάσταση": "status",
      "Ποσό": {
        field: "amount",
        suffix: " €",
        precision: 2
      }
    };
    return _this5;
  }

  _createClass(Orders, [{
    key: "render",
    value: function render() {
      var _this6 = this;

      return _react.default.createElement("div", null, _react.default.createElement(_TableData.default, {
        service: this.props.service,
        TableHeaders: this.tableHeaders,
        onView: function onView(e) {
          return _this6.props.viewOrder(e);
        }
      }));
    }
  }]);

  return Orders;
}(_react.default.Component);

var Info =
/*#__PURE__*/
function (_React$Component2) {
  _inherits(Info, _React$Component2);

  function Info(props) {
    var _this7;

    _classCallCheck(this, Info);

    _this7 = _possibleConstructorReturn(this, _getPrototypeOf(Info).call(this, props));
    _this7.state = {};
    _this7.passwordInputs = {
      "cpass": {
        type: "text",
        placeholder: "Current password",
        columns: "col s12",
        filter: {
          password: true,
          required: true
        }
      },
      "npass": {
        type: "text",
        placeholder: "New password",
        columns: "col s12",
        filter: {
          password: true,
          required: true
        }
      },
      "rpass": {
        type: "text",
        placeholder: "Repeat new password",
        columns: "col s12",
        filter: {
          password: true,
          required: true
        }
      }
    };
    return _this7;
  }

  _createClass(Info, [{
    key: "render",
    value: function render() {
      var _this8 = this;

      return _react.default.createElement("div", {
        className: "Info"
      }, _react.default.createElement("h6", {
        className: "Title_Container"
      }, _react.default.createElement("div", {
        className: "title"
      }, "\u039F\u03B9 \u03C0\u03BB\u03B7\u03C1\u03BF\u03C6\u03BF\u03C1\u03B9\u03B5\u03C2 \u03BC\u03BF\u03C5")), _react.default.createElement("div", {
        className: "Content"
      }, _react.default.createElement(_Form.default, {
        FormInputs: (0, _Merge.default)(_ClientInput.default, this.props.account || {}),
        activeButton: true,
        button: 'Αποθήκευση',
        onSubmit: function onSubmit(d) {
          return _this8.props.onSubmit(d);
        }
      })), _react.default.createElement("h6", {
        className: "Title_Container"
      }, _react.default.createElement("div", {
        className: "title"
      }, "\u0391\u03BB\u03BB\u03B1\u03B3\u03AE \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03CD")), _react.default.createElement("div", {
        className: "Content"
      }, _react.default.createElement(_Form.default, {
        FormInputs: this.passwordInputs,
        activeButton: true,
        button: 'Αλλαγή κωδικού',
        onSubmit: function onSubmit(d) {
          return _this8.props.onChangePassSubmit(d);
        }
      })));
    }
  }]);

  return Info;
}(_react.default.Component);

UserAccount.Inputs = {
  Account: {
    type: Module.Types.Object
  },
  Token: {
    type: Module.Types.Text
  },
  ClassName: {
    type: Module.Types.Text
  },
  baseURL: {
    type: Module.Types.Text,
    defaultValue: "/user"
  }
};
UserAccount.Category = "Sxoinas Packages";
var _default = UserAccount;
exports.default = _default;