"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
var React = require("react");
var productListHeader_1 = require("./products/productListHeader");
var ProductListItem_1 = require("./products/ProductListItem");
var pager_1 = require("../../common/pager");
var routes_1 = require("../../../apiClient/routes");
var httpService_1 = require("../../../services/httpService");
var history_1 = require("../../../history");
var QueryString = require("query-string");
var ProductList = /** @class */ (function (_super) {
    __extends(ProductList, _super);
    function ProductList(props) {
        var _a, _b, _c, _d, _e, _f, _g;
        var _this = _super.call(this, props) || this;
        _this.calculateTotalPages = function (productsAmount) {
            var pageSize = Number(_this.state.activePageSizeExpression);
            var totalPages = Math.floor(productsAmount / pageSize);
            if ((productsAmount % pageSize) > 0) {
                totalPages++;
                _this.setState({ totalPages: totalPages });
            }
            else if (productsAmount === 0) {
                _this.setState({ totalPages: 0 });
            }
            else if (totalPages <= _this.state.pageIndex) {
                _this.setState({ pageIndex: 0 });
            }
            else {
                _this.setState({ totalPages: totalPages });
            }
        };
        _this.handleFilterExpressionChange = function (categoryId) {
            var category = _this.state.productCategories.find(function (i) { return i.id === categoryId; });
            var selectedCategories = [];
            if (category !== undefined) {
                selectedCategories = _this.getProductCategoryParent(category).reverse();
            }
            _this.handleQueryStringChange([
                { propertyName: 'category', value: category === null || category === void 0 ? void 0 : category.id },
                { propertyName: 'pageIndex', value: 0 },
            ]);
            _this.setState({ activeFilterExpression: __assign(__assign({}, _this.state.activeFilterExpression), { productCategoryId: categoryId.toString() }), selectedCategories: selectedCategories, pageIndex: 0 });
        };
        _this.getProductCategoryParent = function (category) {
            var result = [category];
            if (category.parentID !== -1) {
                var parent_1 = _this.state.productCategories.find(function (i) { return i.id === category.parentID; });
                if (parent_1 !== undefined) {
                    result.push.apply(result, _this.getProductCategoryParent(parent_1));
                }
                return result;
            }
            return result;
        };
        // Při změně zobrazit první stránku (pageIndex 0)
        // Lepší řešení mě nenapadlo
        _this.handlePageSizeExpressionChange = function (arg) {
            _this.handleQueryStringChange([
                { propertyName: 'productsOnPage', value: arg.value },
                { propertyName: 'pageIndex', value: 0 },
            ]);
            _this.setState({ activePageSizeExpression: arg.value.toString(), pageIndex: 0 });
        };
        _this.handleSortExpressionChange = function (arg) {
            switch (arg.label) {
                case 'A-Z':
                    _this.handleQueryStringChange([
                        { propertyName: 'sortDirection', value: 'ascending' },
                        { propertyName: 'sortExpression', value: 'Name' },
                        { propertyName: 'sortValue', value: arg.value }
                    ]);
                    _this.setState({
                        activeSortExpression: arg.value,
                        sortItem: {
                            direction: 'ascending',
                            expression: 'Name'
                        }
                    });
                    break;
                case 'Z-A':
                    _this.handleQueryStringChange([
                        { propertyName: 'sortDirection', value: 'descending' },
                        { propertyName: 'sortExpression', value: 'Name' },
                        { propertyName: 'sortValue', value: arg.value }
                    ]);
                    _this.setState({
                        activeSortExpression: arg.value,
                        sortItem: {
                            direction: 'descending',
                            expression: 'Name'
                        }
                    });
                    break;
                case 'Nejdražší':
                    _this.handleQueryStringChange([
                        { propertyName: 'sortDirection', value: 'descending' },
                        { propertyName: 'sortExpression', value: 'Price' },
                        { propertyName: 'sortValue', value: arg.value }
                    ]);
                    _this.setState({
                        activeSortExpression: arg.value,
                        sortItem: {
                            direction: 'descending',
                            expression: 'Price'
                        }
                    });
                    break;
                case 'Nejlevnější':
                    _this.handleQueryStringChange([
                        { propertyName: 'sortDirection', value: 'ascending' },
                        { propertyName: 'sortExpression', value: 'Price' },
                        { propertyName: 'sortValue', value: arg.value }
                    ]);
                    _this.setState({
                        activeSortExpression: arg.value,
                        sortItem: {
                            direction: 'ascending',
                            expression: 'Price'
                        }
                    });
                    break;
                default:
                    break;
            }
        };
        _this.handlePageChange = function (newPageIndex) {
            _this.handleQueryStringChange([{ propertyName: 'pageIndex', value: newPageIndex }]);
            _this.setState({ pageIndex: newPageIndex });
        };
        _this.handlePageShift = function (shift) {
            var _a = _this.state, pageIndex = _a.pageIndex, totalPages = _a.totalPages;
            if (shift === 1) {
                if ((pageIndex + 1) < totalPages) {
                    _this.handleQueryStringChange([{ propertyName: 'pageIndex', value: (pageIndex + 1) }]);
                    _this.setState({ pageIndex: pageIndex + 1 });
                }
            }
            else {
                if ((pageIndex - 1) >= 0) {
                    _this.handleQueryStringChange([{ propertyName: 'pageIndex', value: (pageIndex - 1) }]);
                    _this.setState({ pageIndex: pageIndex - 1 });
                }
            }
        };
        _this.handleQueryStringChange = function (params) {
            var parsed = QueryString.parse(window.location.search);
            var query = __assign({}, parsed);
            params.forEach(function (item) {
                var _a;
                query = __assign(__assign({}, query), (_a = {}, _a[item.propertyName] = item.value, _a));
            });
            var stringified = QueryString.stringify(query);
            history_1.default.replace({
                pathname: history_1.default.location.pathname,
                search: '?' + stringified
            });
        };
        var parsed = QueryString.parse(window.location.search);
        _this.state = {
            activeFilterExpression: {
                productCategoryId: (_a = parsed.category) !== null && _a !== void 0 ? _a : '0',
                searchString: (_b = parsed.searchString) !== null && _b !== void 0 ? _b : ''
            },
            activePageSizeExpression: (_c = parsed.productsOnPage) !== null && _c !== void 0 ? _c : '8',
            activeSortExpression: (_d = parsed.sortValue) !== null && _d !== void 0 ? _d : '1',
            products: Array(),
            productCategories: Array(),
            selectedCategories: Array(),
            pageIndex: (_e = parsed.pageIndex) !== null && _e !== void 0 ? _e : 0,
            sortItem: {
                direction: (_f = parsed.sortDirection) !== null && _f !== void 0 ? _f : 'ascending',
                expression: (_g = parsed.sortExpression) !== null && _g !== void 0 ? _g : 'Name'
            },
            totalPages: 1,
            isLoaded: false
        };
        return _this;
    }
    ProductList.prototype.componentDidMount = function () {
        return __awaiter(this, void 0, void 0, function () {
            var allProducts, allCategories, pagedQuery;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        document.title = "Produkty";
                        allProducts = {};
                        allCategories = Array();
                        pagedQuery = {
                            filter: this.state.activeFilterExpression,
                            pageIndex: this.state.pageIndex,
                            pageSize: this.state.activePageSizeExpression,
                            sorting: [this.state.sortItem]
                        };
                        return [4 /*yield*/, httpService_1.default.post(routes_1.ProductController_GetProducts, pagedQuery).then(function (response) {
                                allProducts = response.data;
                                _this.calculateTotalPages(response.data.totalCount);
                            })
                                .catch(function (e) {
                                console.log(e);
                                _this.setState(__assign({}, _this.state));
                            })];
                    case 1:
                        _a.sent();
                        return [4 /*yield*/, httpService_1.default.get(routes_1.ProductController_GetCategories).then(function (response) {
                                allCategories = response.data;
                            })
                                .catch(function (e) {
                                console.log(e);
                                _this.setState(__assign({}, _this.state));
                            })];
                    case 2:
                        _a.sent();
                        this.setState({
                            activeFilterExpression: __assign(__assign({}, this.state.activeFilterExpression), { searchString: this.props.searchString }),
                            products: allProducts.data,
                            productCategories: allCategories,
                            isLoaded: true
                        });
                        return [2 /*return*/];
                }
            });
        });
    };
    ProductList.prototype.componentDidUpdate = function (prevProps, prevState) {
        var _this = this;
        if (this.state.activeFilterExpression !== prevState.activeFilterExpression ||
            this.state.pageIndex !== prevState.pageIndex ||
            this.state.activePageSizeExpression !== prevState.activePageSizeExpression ||
            this.state.sortItem !== prevState.sortItem ||
            this.props.searchString !== prevProps.searchString) {
            var _a = this.state, activeFilterExpression = _a.activeFilterExpression, activePageSizeExpression = _a.activePageSizeExpression, pageIndex = _a.pageIndex, sortItem = _a.sortItem;
            var allProducts_1 = {};
            var pagedQuery = {
                filter: __assign(__assign({}, activeFilterExpression), { searchString: this.props.searchString }),
                pageIndex: pageIndex,
                pageSize: activePageSizeExpression,
                sorting: [sortItem]
            };
            httpService_1.default.post(routes_1.ProductController_GetProducts, pagedQuery).then(function (response) {
                allProducts_1 = response.data;
                _this.calculateTotalPages(allProducts_1.totalCount);
                _this.setState({ products: allProducts_1.data, isLoaded: true });
            })
                .catch(function (e) {
                console.log(e);
                _this.setState(__assign({}, _this.state));
            });
        }
    };
    ProductList.prototype.render = function () {
        var _a = this.state, activeFilterExpression = _a.activeFilterExpression, activePageSizeExpression = _a.activePageSizeExpression, activeSortExpression = _a.activeSortExpression, isLoaded = _a.isLoaded, pageIndex = _a.pageIndex, products = _a.products, productCategories = _a.productCategories, selectedCategories = _a.selectedCategories, totalPages = _a.totalPages;
        var onAddToCartClick = this.props.onAddToCartClick;
        return (React.createElement(React.Fragment, null, isLoaded && products !== undefined
            ? React.createElement("section", { className: "featured" },
                React.createElement("div", { className: "container" },
                    React.createElement(productListHeader_1.default, { activeFilterExpression: activeFilterExpression.productCategoryId.toString(), activeSortExpression: activeSortExpression, activePageSizeExpression: activePageSizeExpression, categories: __spreadArray([], productCategories, true), onFilterExpressionChange: this.handleFilterExpressionChange, onPageSizeExpressionChange: this.handlePageSizeExpressionChange, onSortExpressionChange: this.handleSortExpressionChange, productItemsAmount: products.length, selectedCategories: selectedCategories }),
                    React.createElement("div", { className: "row featured__filter" }, products.map(function (product) {
                        return React.createElement(ProductListItem_1.default, { key: "productListItem-".concat(product.id), onAddToCartClick: onAddToCartClick, product: product });
                    })),
                    React.createElement(pager_1.Pager, { onPageChange: this.handlePageChange, onPageShift: this.handlePageShift, pageIndex: pageIndex, totalPages: totalPages })))
            : null));
    };
    return ProductList;
}(React.Component));
exports.default = ProductList;
//# sourceMappingURL=productList.js.map