"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("./CartPage.css");

var _API = _interopRequireDefault(require("../../Services/API"));

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

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

var _Step = _interopRequireDefault(require("@material-ui/core/Step"));

var _StepLabel = _interopRequireDefault(require("@material-ui/core/StepLabel"));

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

var _Typography = _interopRequireDefault(require("@material-ui/core/Typography"));

var _CustomTable = _interopRequireDefault(require("../../Modules/CustomTable"));

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

var _Table = _interopRequireDefault(require("../../Modules/Table"));

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

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

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

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

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

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

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

var _Stepper = _interopRequireDefault(require("../../Modules/Stepper"));

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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }

function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, 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 _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); }

// import braintree from 'braintree-web';
var braintree = window.braintree;
var CLIENT_TOKEN, INSTANCE;
var Module = _modularityFront.default.Module;

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

  function CartPage(props) {
    var _this;

    _classCallCheck(this, CartPage);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(CartPage).call(this, props));
    _this.state = {
      activeStep: 0,
      products: [],
      productHeaders: {
        '#': '-index-',
        image: "image",
        Name: "name",
        "Item Price": {
          field: "price",
          suffix: " €"
        },
        Quantity: "quantity",
        Total: {
          field: "amount",
          suffix: " €"
        }
      },
      selectedAddress: {},
      selectedBillingAddress: {},
      selectedShipping: {},
      user: {},
      clientInputs: {}
    };
    _this.formRef = _react.default.createRef();
    _this.api = new _API.default('/orders', _this.Token.value);
    _this.addressRepo = new _Repository.default('addresses', _this.Token.value);
    _this.accountRepo = new _Repository.default('accounts', _this.Token.value);
    _this.userRepo = new _UserService.default({
      Token: function Token(t) {}
    });
    _this.state = _objectSpread({}, _this.state, _this._load());

    _this.Products.onUpdate(function (data) {
      _this.setState(_this._load());
    });

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

    _this.handleToken();

    return _this;
  }

  _createClass(CartPage, [{
    key: "_product_to_table",
    value: function _product_to_table(prods) {
      return Object.keys(prods).map(function (key, index) {
        var _prods$key = prods[key],
            name = _prods$key.name,
            price = _prods$key.price,
            quantity = _prods$key.quantity,
            image = _prods$key.image;
        return {
          id: key,
          image: image,
          name: name,
          price: parseFloat(price.toFixed(2)),
          quantity: quantity,
          amount: parseFloat((price * quantity).toFixed(2))
        };
      });
    }
  }, {
    key: "_load",
    value: function _load() {
      var _this2 = this;

      var withShipping = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

      var products = this._product_to_table(this.Products.value || {});

      var total = Object.keys(this.Products.value || {}).reduce(function (tot, item) {
        return tot + _this2.Products.value[item].price * _this2.Products.value[item].quantity;
      }, withShipping ? this.state.selectedShipping.price || 0 : 0); //start with shipping

      var fpa = 0.24 * total;
      return {
        products: products,
        total: total,
        fpa: fpa
      };
    }
  }, {
    key: "routeMatch",
    value: function routeMatch() {
      return this.RoutingSystem.getRoute().url.startsWith(this.baseURL.value);
    }
  }, {
    key: "requestClientToken",
    value: function requestClientToken(token) {
      var _this3 = this;

      this.baseAPI = new _API.default("", token);
      this.baseAPI.get("/client_token").then(function (res) {
        var ctoken = res.clientToken;
        _this3.CLIENT_TOKEN = ctoken;

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

      if (this.Token.value) {
        this.requestClientToken(this.Token.value);
      }

      this.api.setToken(this.Token.value);
      this.accountRepo.setToken(this.Token.value);
      this.addressRepo.setToken(this.Token.value);
      this.getUserData();
    }
  }, {
    key: "showPayment",
    value: function showPayment() {
      braintree.dropin.create({
        authorization: this.CLIENT_TOKEN,
        container: '#dropin-container',
        paypal: {
          flow: 'vault'
        }
      }, function (createErr, instance) {
        INSTANCE = instance;
      });
    }
  }, {
    key: "makePayment",
    value: function makePayment() {
      return new Promise(function (resolve, reject) {
        INSTANCE.requestPaymentMethod(function (err, payload) {
          // Submit payload.nonce to your server
          if (err) {
            return reject(err);
          }

          resolve(payload);
        });
      });
    }
  }, {
    key: "makeOrder",
    value: function makeOrder() {
      var _this4 = this;

      // FIX PRICE only 2 decimal places
      return this.makePayment().then(function (payload) {
        var products = _this4.state.products;
        var amount = parseFloat(_this4.state.total.toFixed(2));
        var nonce = payload.nonce;
        var customer = _this4.state.customer;
        var shipping = _this4.state.shipping;
        var ShippingID = _this4.state.selectedShipping.id;
        var AddressID = _this4.state.selectedAddress.id;

        _this4.api.post('/submit', {
          products: products,
          amount: amount,
          nonce: nonce,
          customer: customer,
          Shipping_id: ShippingID,
          Addresses_id: AddressID
        }).then(function (res) {
          console.log(res);
          alert("Success");

          _this4.CoreSystem.go('/user/orders');
        }).catch(function (err) {
          alert(err);
        });
      });
    }
  }, {
    key: "makeInputs",
    value: function makeInputs(struct) {
      var res = _objectSpread({}, struct);

      var user = this.state.user;
      if (!user.Account) return res;
      var acc = user.Account;

      for (var i in res) {
        res[i].value = acc[i] || '';
      }

      return res;
    }
  }, {
    key: "makeAddresses",
    value: function makeAddresses() {
      var user = this.state.user;
      if (!user.Addresses) return [];
      return user.Addresses || [];
    }
  }, {
    key: "makeAddress",
    value: function makeAddress(struct, address) {
      if (!address) return struct;

      for (var i in struct) {
        struct[i].value = address[i] || '';
      }

      return struct;
    }
  }, {
    key: "updateAccount",
    value: function updateAccount(acc) {
      this.setState({
        formAccount: acc
      });
    }
  }, {
    key: "getUserData",
    value: function getUserData() {
      var _this5 = this;

      return this.userRepo.getUser(this.Token.value).then(function (user) {
        return _this5.setState({
          user: user
        });
      }).then(function () {
        return _this5.makeInputs(_ClientInput.default);
      }).then(function (clientInputs) {
        return _this5.setState({
          clientInputs: clientInputs
        });
      });
    }
  }, {
    key: "verifyOrderDetails",
    value: function verifyOrderDetails() {
      var _this6 = this;

      _Toast.default.clear();

      var accid = this.state.user.Account && this.state.user.Account.id;
      return Promise.resolve(true).then(function () {
        return _this6.state.formAccount && accid && _this6.accountRepo.update(accid, _this6.state.formAccount);
      }).then(function () {
        return _this6.getUserData();
      }).then(function () {
        if (!_this6.state.selectedAddress || !_this6.state.selectedAddress.id) {
          // this.CoreSystem.go('/orders/verify');
          _Toast.default.warning(_DictionaryService.default.get("Select address!"));

          throw 'no selected Address';
        }

        if (!_this6.state.selectedBillingAddress || !_this6.state.selectedBillingAddress.id) {
          // this.CoreSystem.go('/orders/verify');
          _Toast.default.warning(_DictionaryService.default.get("Select billing address!"));

          throw 'no selected Address';
        }

        if (!_this6.state.selectedShipping || !_this6.state.selectedShipping.id) {
          // this.CoreSystem.go('/orders/verify');
          _Toast.default.warning(_DictionaryService.default.get("Select shipping method!"));

          throw 'no selected Shipping';
        }
      });
    }
  }, {
    key: "onNext",
    value: function onNext(step) {
      console.log(step);
    }
  }, {
    key: "getSteps",
    value: function getSteps() {
      var _this7 = this;

      return [{
        title: _DictionaryService.default.get("Cart"),
        url: '/orders',
        content: this.getStepContent(0),
        button: _DictionaryService.default.get("Checkout"),
        resolve: function resolve() {
          _this7.setState(_this7._load(false));
        }
      }, {
        title: _DictionaryService.default.get("Order Info"),
        url: '/orders/verify',
        content: this.getStepContent(1),
        button: _DictionaryService.default.get("Payment"),
        resolve: function resolve() {
          return _this7.getUserData();
        }
      }, {
        title: _DictionaryService.default.get("Payment"),
        url: '/orders/payment',
        content: this.getStepContent(2),
        button: _DictionaryService.default.get("Finish"),
        resolve: function resolve() {
          _this7.setState(_this7._load(true));

          return _this7.verifyOrderDetails();
        },
        postResolve: function postResolve() {
          return _this7.showPayment();
        }
      }];
    }
  }, {
    key: "getStepContent",
    value: function getStepContent(stepIndex) {
      var _this8 = this;

      switch (stepIndex) {
        case 0:
          return _react.default.createElement("div", null, _react.default.createElement("div", {
            className: "headers"
          }), _react.default.createElement(_Table.default, {
            TableData: [].concat(_toConsumableArray(this.state.products), [{
              quantity: "ΦΠΑ",
              amount: (this.state.fpa || 0).toFixed(2)
            }, {
              quantity: _react.default.createElement("b", null, _DictionaryService.default.get("Total")),
              amount: _react.default.createElement("b", null, this.state.total.toFixed(2) + ' €')
            }]),
            TableHeaders: this.state.productHeaders,
            TableClass: "products_table"
          }));

        case 1:
          // let addresses = this.makeAddresses();
          return _react.default.createElement("div", null, _react.default.createElement("div", {
            className: "headers"
          }, _DictionaryService.default.get("Please fill your Information")), _react.default.createElement(_reactMaterialize.Card, null, _react.default.createElement(_Form.default, {
            FormInputs: this.state.clientInputs,
            activeButton: false,
            formData: function formData(data) {
              return _this8.updateAccount(data);
            },
            ref: this.formRef
          })), _react.default.createElement("div", {
            className: "headers"
          }, _DictionaryService.default.get("Select delivery address")), _react.default.createElement(_AddressesDisplay.default, {
            service: this.addressRepo,
            update: function update(v) {
              return _this8.setState({
                __V: v
              });
            },
            onSelect: function onSelect(selectedAddress) {
              _this8.setState({
                selectedAddress: selectedAddress
              });
            }
          }), _react.default.createElement("div", {
            className: "headers"
          }, _DictionaryService.default.get("Select billing address")), _react.default.createElement(_AddressesDisplay.default, {
            service: this.addressRepo,
            update: function update(v) {
              return _this8.setState({
                __V: v
              });
            },
            onSelect: function onSelect(selectedBillingAddress) {
              _this8.setState({
                selectedBillingAddress: selectedBillingAddress
              });
            }
          }), _react.default.createElement(Shippings, {
            onSelect: function onSelect(selectedShipping) {
              _this8.setState({
                selectedShipping: selectedShipping
              });
            }
          }));

        case 2:
          return _react.default.createElement("div", null, _react.default.createElement("div", null, _react.default.createElement("div", {
            className: "headers"
          }), _react.default.createElement(_Table.default, {
            TableData: [].concat(_toConsumableArray(this.state.products), [{
              quantity: _DictionaryService.default.get("Shipping Cost"),
              amount: (this.state.selectedShipping.price || 0).toFixed(2)
            }, {
              quantity: "ΦΠΑ",
              amount: this.state.fpa.toFixed(2)
            }, {
              quantity: _react.default.createElement("b", null, _DictionaryService.default.get("Total")),
              amount: _react.default.createElement("b", null, this.state.total.toFixed(2) + ' €')
            }]),
            TableHeaders: this.state.productHeaders,
            TableClass: "products_table"
          })), _react.default.createElement("span", null, _DictionaryService.default.get("Payment")), _react.default.createElement("div", {
            id: "dropin-container"
          }), _react.default.createElement(_Button.default, {
            onClick: function onClick() {
              return _this8.makeOrder();
            }
          }, _DictionaryService.default.get("Submit order")));
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this9 = this;

      return _react.default.createElement("div", {
        className: "stepper_container"
      }, _react.default.createElement(_Stepper.default, {
        className: "row stepper",
        steps: this.getSteps(),
        baseURL: this.baseURL.value,
        onNext: function onNext(step) {
          return _this9.onNext(step);
        },
        lock: this.state.lock
      }), _get(_getPrototypeOf(CartPage.prototype), "render", this).call(this));
    }
  }]);

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

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

  function Shippings(props) {
    var _this10;

    _classCallCheck(this, Shippings);

    _this10 = _possibleConstructorReturn(this, _getPrototypeOf(Shippings).call(this, props));
    _this10.state = {
      shippings: [],
      selected: {}
    };
    _this10.repo = new _Repository.default('shipping');

    _this10.repo.getPage(1, 1000).then(function (shippings) {
      return _this10.setState({
        shippings: shippings
      });
    });

    return _this10;
  }

  _createClass(Shippings, [{
    key: "select",
    value: function select(selected) {
      this.setState({
        selected: selected
      });
      this.props.onSelect && this.props.onSelect(selected);
    }
  }, {
    key: "render",
    value: function render() {
      var _this11 = this;

      var selected = this.state.selected;
      var shippings = this.state.shippings;
      return _react.default.createElement("div", {
        className: "shipping-items"
      }, _react.default.createElement("div", {
        className: "headers"
      }, _DictionaryService.default.get("Select shipping method")), shippings.map(function (ship) {
        return _react.default.createElement("div", {
          key: ship.id,
          className: "card cursor shipping-item " + (ship.id === selected.id ? 'selected' : ''),
          onClick: function onClick() {
            return _this11.select(ship);
          }
        }, _react.default.createElement("div", {
          className: "name"
        }, ship.name), _react.default.createElement("div", {
          className: "price"
        }, "+ ", ship.price.toFixed(2), " \u20AC"));
      }));
    }
  }]);

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

CartPage.EditPosition = "center";
CartPage.Inputs = {
  Products: {
    type: Module.Types.Object
  },
  Token: {
    type: Module.Types.Text
  },
  baseURL: {
    type: Module.Types.Text,
    defaultValue: "/orders"
  }
};
CartPage.Outputs = {
  selectedProduct: {}
};
CartPage.Category = "Sxoinas Packages";
var _default = CartPage;
exports.default = _default;