"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 _Pagination = _interopRequireDefault(require("../../Modules/Pagination"));

var _Card = _interopRequireDefault(require("../../Modules/Card"));

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

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

var _FilterModule = _interopRequireDefault(require("../../Modules/FilterModule"));

var _Done = _interopRequireDefault(require("@material-ui/icons/Done"));

var _searchbar = _interopRequireDefault(require("../../Modules/searchbar"));

var _Chip = _interopRequireDefault(require("../../Modules/Chip"));

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

var _DropdownFilter = _interopRequireDefault(require("../../Modules/UserInputs/DropdownFilter"));

require("./presentation1.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 _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 _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 _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 PresantationModule =
/*#__PURE__*/
function (_Modularity$Module) {
  _inherits(PresantationModule, _Modularity$Module);

  function PresantationModule(props) {
    var _this;

    _classCallCheck(this, PresantationModule);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(PresantationModule).call(this, props));
    _this.state = {
      FilterInputs: [],
      page: 1,
      totalPages: 1,
      products: {},
      search: {},
      filterVisible: false
    };
    _this.orderingFilter = _this.getOrderingFilter();
    _this.perPage = 9;

    _this.Repository.onUpdate(function (repo) {
      return _this.updateRepository(repo);
    });

    _this.filters = [];
    _this.search = {
      type: "search",
      values: [],
      field: "name,description"
    };

    _this.setSearch(_this.search);

    _this.Filters.onUpdate(function (v) {
      return _this.updateFilters(v);
    });

    var session = sessionStorage.getItem("FilterInputs");

    if (!session) {
      _this.getModel();
    } else {
      _this.state.FilterInputs = JSON.parse(session);
      _this.filters = _this.state.FilterInputs;

      _this.update();
    }

    return _this;
  }

  _createClass(PresantationModule, [{
    key: "getModel",
    value: function getModel() {
      var _this2 = this;

      var ProductsRepo = new _Repository.default("products");
      ProductsRepo.model().then(function (model) {
        var inputs = [];

        for (var i in model) {
          if (model[i].Filter) {
            //TODO update these 2 lines logic
            if (model[i].Filter.type === 'search' && model[i].Filter.field === 'name') {
              _this2.setSearch(model[i].Filter);
            } else {
              inputs.push(model[i].Filter);
            }
          }
        }

        return inputs;
      }).then(function (v) {
        return v.reduce(function (initial, b) {
          return b.order > -1 ? initial.push(b) && initial : initial;
        }, []);
      }).then(function (v) {
        return v.sort(function (a, b) {
          return a.order - b.order;
        });
      }).then(function (v) {
        _this2.setState({
          FilterInputs: v
        });

        sessionStorage.setItem("FilterInputs", JSON.stringify(v));

        _this2.update();
      });
    }
  }, {
    key: "updateFilters",
    value: function updateFilters(filters) {
      if (filters === undefined) {
        return;
      }

      this.filters = filters;
      this.update();
      this.setState({
        FilterInputs: filters
      });
      sessionStorage.setItem("FilterInputs", JSON.stringify(filters));
    }
  }, {
    key: "getOrderingFilter",
    value: function getOrderingFilter() {
      return sessionStorage.getItem("Ordering") && JSON.parse(sessionStorage.getItem("Ordering")) || {
        type: 'ascending',
        options: {
          'price': 'Τιμή',
          'name': 'Όνομα προϊόντος'
        },
        field: 'price',
        required: true,
        value: 'price'
      };
    }
  }, {
    key: "update",
    value: function update() {
      sessionStorage.setItem("Ordering", JSON.stringify(this.orderingFilter));
      this.updateRepository(new _Repository.default('products', null, [].concat(_toConsumableArray(this.filters), [this.orderingFilter, this.search])));
    }
  }, {
    key: "updateRepository",
    value: function updateRepository(repo) {
      this.back_service = repo;
      this.getData();
    }
  }, {
    key: "updatePattern",
    value: function updatePattern(v) {
      window.history.replaceState({}, '', '/search/' + v); // Implement Into CoreSystem
    }
  }, {
    key: "getData",
    value: function getData() {
      var _this3 = this;

      var page = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
      this.back_service.count().then(function (result) {
        var totalPages = Math.ceil(result[0].counter / _this3.perPage);

        _this3.setState({
          totalPages: totalPages
        });
      });
      this.back_service.getPage(page, this.perPage).then(function (result) {
        return _this3.parseData(result);
      }).then(function (data) {
        _this3.setState({
          products: data
        });

        _this3.forceUpdate();
      }).catch(function (e) {
        console.log(e);
      });
    }
  }, {
    key: "parseData",
    value: function parseData(result) {
      return result.map(function (item) {
        var val = {
          id: item.id,
          name: item.name,
          description: item.description || "",
          shortdescription: item.shortdescription || "",
          price: item.price,
          image: item.image || "/logo.png",
          quantity: 1
        };
        return val;
      });
    }
  }, {
    key: "setSearch",
    value: function setSearch(filter) {
      var route = (this.RoutingSystem.getRoute().params || {}).value;
      filter.values = [route || ''];
      filter.field = "name,description";
      sessionStorage.setItem("SearchFilter", JSON.stringify(filter));
      this.search = filter; //this.update();
    }
  }, {
    key: "setSearchFilter",
    value: function setSearchFilter(v) {
      var filter = {
        type: "search",
        values: [v],
        field: "name,description"
      };
      sessionStorage.setItem("SearchFilter", JSON.stringify(filter));
      this.search = filter;
      this.updatePattern(v);
      this.update();
    }
  }, {
    key: "pageChanged",
    value: function pageChanged(v) {
      this.getData(v);
    }
  }, {
    key: "addProduct",
    value: function addProduct(v) {
      this.selectedProduct.set(v);

      _Toast.default.success(v.name + " added to your cart");

      this.forceUpdate();
    }
  }, {
    key: "render",
    value: function render() {
      var _this4 = this;

      var page = this.state.page;
      var totalPages = this.state.totalPages;
      return _react.default.createElement("div", {
        className: "present_container"
      }, _react.default.createElement(_reactMaterialize.Row, null, _react.default.createElement(_reactMaterialize.Col, {
        className: "filter_container " + (this.state.filterVisible && 'show'),
        l: 3
      }, _react.default.createElement(_FilterModule.default, {
        className: "filter_layout",
        Inputs: this.state.FilterInputs,
        Filters: function Filters(filters) {
          return _this4.updateFilters(filters);
        }
      }), _react.default.createElement("div", {
        className: "badge",
        onClick: function onClick() {
          _this4.setState({
            filterVisible: !_this4.state.filterVisible
          });
        }
      }, _react.default.createElement("i", {
        className: "fa fa-filter"
      }))), _react.default.createElement(_reactMaterialize.Col, {
        l: 9
      }, _react.default.createElement("div", {
        className: "chips_container"
      }, _react.default.createElement(_searchbar.default, {
        SearchBar: {
          defaultValue: (this.RoutingSystem.getRoute().params || {}).value
        },
        SearchData: function SearchData(v) {
          return _this4.setSearchFilter(v);
        }
      }), _react.default.createElement("div", {
        className: "filters"
      }, _react.default.createElement("div", {
        className: "orderBy"
      }, _react.default.createElement("div", {
        className: "tool",
        onClick: function onClick() {
          _this4.orderingFilter = _objectSpread({}, _this4.orderingFilter, {
            type: _this4.orderingFilter.type === "ascending" ? 'descending' : 'ascending'
          });

          _this4.update();
        }
      }, _react.default.createElement("i", {
        className: "fa fa-sort-" + (this.orderingFilter.type === "ascending" ? 'up' : 'down')
      })), _react.default.createElement(_DropdownFilter.default, {
        filter: this.orderingFilter,
        defaultValue: this.orderingFilter.field,
        Filters: function Filters(data) {
          var field = data.values[0];
          _this4.orderingFilter = _objectSpread({}, _this4.orderingFilter, {
            field: field,
            value: field
          });

          _this4.update();
        }
      })), _react.default.createElement("div", {
        className: "chip_module"
      }, _react.default.createElement(_Chip.default, {
        Inputs: this.state.FilterInputs,
        Filters: function Filters(filters) {
          return _this4.updateFilters(filters);
        }
      })))), _react.default.createElement("div", {
        className: "products_container"
      }, _react.default.createElement(PresentData, {
        products: this.state.products,
        addProduct: function addProduct(e) {
          return _this4.addProduct(e);
        },
        onClick: function onClick(p) {
          _this4.CoreSystem.go('/product/' + p.id);
        }
      }), _react.default.createElement(_Pagination.default, {
        selected: page,
        lastPage: totalPages,
        onPage: function onPage(v) {
          return _this4.pageChanged(v);
        }
      }))), _get(_getPrototypeOf(PresantationModule.prototype), "render", this).call(this)));
    }
  }]);

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

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

  function PresentData(props) {
    _classCallCheck(this, PresentData);

    return _possibleConstructorReturn(this, _getPrototypeOf(PresentData).call(this, props));
  }

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

      if (!this.props.products.length) {
        return _react.default.createElement("h6", null, _DictionaryService.default.get("No products"));
      }

      var prods = this.props.products;
      var prodList = Object.keys(prods).map(function (item, index) {
        var key = item; //item.id;

        var p = prods[key]; //item;

        return _react.default.createElement(_Card.default, {
          id: key,
          key: p.name,
          className: "col s12 m6 l4",
          CardTitle: p.name,
          Price: p.price,
          CardBody: _react.default.createElement("span", {
            dangerouslySetInnerHTML: {
              __html: p.shortdescription
            }
          }),
          CardImage: p.image,
          product: function product(prod) {
            return _this5.props.addProduct(p);
          },
          onClick: function onClick() {
            return _this5.props.onClick(p);
          }
        });
      });
      return _react.default.createElement(_reactMaterialize.Row, null, prodList);
    }
  }]);

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

PresantationModule.EditPosition = "center";
PresantationModule.Inputs = {
  Repository: {
    type: Module.Types.Object
  },
  Page: {
    type: Module.Types.Number
  },
  Url: {
    type: Module.Types.Text,
    defaultValue: ""
  },
  Filters: {
    type: Module.Types.Object
  }
};
PresantationModule.Outputs = {
  selectedProduct: {}
};
PresantationModule.Category = "Sxoinas Packages";
var _default = PresantationModule;
exports.default = _default;