"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 react_router_1 = require("react-router");
var AboutUs_1 = require("../components/User/components/AboutUs");
var AccountInfo_1 = require("../components/User/components/Account/AccountInfo");
var AccountHeader_1 = require("../components/User/components/Account/AccountHeader");
var AddressManagement_1 = require("../components/User/components/Account/AddressManagement");
var ChangePasswordForm_1 = require("../components/User/components/Account/ChangePasswordForm");
var Contacts_1 = require("../components/User/components/Contacts");
var checkout_1 = require("../components/User/components/checkout");
var Delivery_1 = require("../components/User/components/Delivery");
var Login_1 = require("../components/User/components/Security/Login");
var OrderCompleted_1 = require("../components/User/components/OrderCompleted");
var OrderDetail_1 = require("../components/User/components/Account/OrderDetail");
var OrderList_1 = require("../components/User/components/Account/OrderList");
var PasswordRecovery_1 = require("../components/User/components/Security/PasswordRecovery");
var PasswordReset_1 = require("../components/User/components/Security/PasswordReset");
var productList_1 = require("../components/User/components/productList");
var productDetail_1 = require("../components/User/components/productDetail");
var shoppingCart_1 = require("../components/User/components/shoppingCart");
var Signup_1 = require("../components/User/components/Security/Signup");
var TradeTerms_1 = require("../components/User/components/TradeTerms");
var userLayout_1 = require("../components/userLayout");
var localStorageService_1 = require("../services/localStorageService");
var react_toastify_1 = require("react-toastify");
var routes_1 = require("../apiClient/routes");
var httpService_1 = require("../services/httpService");
var UserRoutes = /** @class */ (function (_super) {
    __extends(UserRoutes, _super);
    function UserRoutes() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            cartItemsCount: 0,
            cartItems: Array(),
            displayErrorMessage: false,
            userName: '',
            searchString: ''
        };
        _this.getUserShoppingCart = function (user) { return __awaiter(_this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, httpService_1.default.get((0, routes_1.OrderController_GetUserShoppingCartItems)(user.unique_name.toString())).then(function (response) {
                            _this.setState({ cartItemsCount: response.data.length, cartItems: response.data, displayErrorMessage: false, userName: "".concat(user.firstName || 'Účet', " ").concat(user.lastName) });
                        }).catch(function (e) {
                            console.log(e);
                            _this.setState(__assign({}, _this.state));
                        })];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        }); };
        // Adds new product to the cart or raise the amount of already existing product in the cart
        _this.handleAddToCart = function (productId, amount) { return __awaiter(_this, void 0, void 0, function () {
            var cartItemsCount, cartItems, cartItem, errorMessage, user, _a, _b, item, index;
            var _this = this;
            var _c;
            return __generator(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        cartItemsCount = this.state.cartItemsCount;
                        cartItems = __spreadArray([], this.state.cartItems, true);
                        cartItem = {
                            productID: productId,
                            amount: amount
                        };
                        errorMessage = '';
                        user = (0, localStorageService_1.GetObject)();
                        if (!(user !== null)) return [3 /*break*/, 2];
                        _b = (_a = Promise).resolve;
                        return [4 /*yield*/, httpService_1.default.post((0, routes_1.OrderController_AddOrderItem)(user.unique_name.toString()), cartItem, { validateStatus: function (status) { return status <= 400; } }).then(function (response) {
                                if (response.status == 200) {
                                    //console.log('Pridano do kosiku (prihlaseny uzivatel): ', response.data);
                                    _this.setState({ cartItemsCount: response.data.amount });
                                }
                                else {
                                    errorMessage = 'Chyba';
                                    react_toastify_1.toast.error("Omlouv\u00E1me se, ale tato polo\u017Eka ji\u017E nen\u00ED skladem!", {
                                        position: "top-right",
                                        autoClose: 3000,
                                        hideProgressBar: true,
                                        closeOnClick: true,
                                        pauseOnHover: false,
                                        draggable: true,
                                        progress: undefined,
                                    });
                                }
                            }).catch(function (e) {
                                console.log(e);
                                _this.setState(__assign({}, _this.state));
                            })];
                    case 1:
                        _b.apply(_a, [_d.sent()]);
                        return [3 /*break*/, 3];
                    case 2:
                        (0, localStorageService_1.AddItemToShoppingCart)(cartItem); // add item to local storage
                        _d.label = 3;
                    case 3:
                        if (!errorMessage) {
                            item = cartItems.find(function (i) { return i.productID === productId; });
                            if (item !== undefined) { // if the item is already in shopping cart
                                index = cartItems.indexOf(item);
                                cartItems[index] = __assign({}, item); // make copy of item object
                                cartItems[index].amount += amount; // change the amount
                                this.setState({ cartItems: cartItems }); // save new array
                                if (this.props.history.location.pathname !== "/cart") {
                                    react_toastify_1.toast.success("\uD83D\uDC4D Polo\u017Eka \"".concat((_c = cartItems.find(function (i) { return i.productID === productId; })) === null || _c === void 0 ? void 0 : _c.name, "\" byla vlo\u017Eena do ko\u0161\u00EDku!"), {
                                        position: "top-right",
                                        autoClose: 3000,
                                        hideProgressBar: true,
                                        closeOnClick: true,
                                        pauseOnHover: false,
                                        draggable: true,
                                        progress: undefined,
                                    });
                                }
                                //console.log("Pridan item, ktery je jiz v kosiku (zvysil se pouze pocet kusu v kosiku)");
                            }
                            else { // item is not in the array => load it from server
                                httpService_1.default.get((0, routes_1.ProductController_GetProduct)(productId.toString())).then(function (response) {
                                    var _a;
                                    var product = response.data;
                                    var cartItem = {
                                        id: 0,
                                        productID: product.id,
                                        name: product.name,
                                        price: (product.reducedPrice != undefined && product.reducedPrice > 0 && product.reducedPrice < product.price) ? product.reducedPrice : product.price,
                                        amount: amount,
                                        availableQuantity: product.availableQuantity,
                                        productCategoryID: product.productCategoryID,
                                        productCategoryName: product.productCategoryName,
                                        productImageID: product.productImageIDs[0]
                                    };
                                    cartItems.push(cartItem);
                                    _this.setState({ cartItems: cartItems, cartItemsCount: (cartItemsCount + 1) });
                                    //console.log("Pridan item, ktery jeste neni v kosiku (produkt nacten ze serveru a vlozen do pole)");
                                    react_toastify_1.toast.success("\uD83D\uDC4D Polo\u017Eka \"".concat((_a = cartItems.find(function (i) { return i.productID === productId; })) === null || _a === void 0 ? void 0 : _a.name, "\" byla vlo\u017Eena do ko\u0161\u00EDku!"), {
                                        position: "top-right",
                                        autoClose: 3000,
                                        hideProgressBar: true,
                                        closeOnClick: true,
                                        pauseOnHover: false,
                                        draggable: true,
                                        progress: undefined,
                                    });
                                })
                                    .catch(function (e) {
                                    console.log(e);
                                    _this.setState(__assign({}, _this.state));
                                });
                            }
                        }
                        return [2 /*return*/];
                }
            });
        }); };
        // Deletes an item from the shopping cart
        _this.handleDeleteFromCart = function (productId) {
            var cartItems = _this.state.cartItems;
            var cartItem = {
                productID: productId,
                amount: 0
            };
            var user = (0, localStorageService_1.GetObject)();
            if (user !== null) {
                httpService_1.default.post((0, routes_1.OrderController_DeleteOrderItem)(user.unique_name.toString()), cartItem, { validateStatus: function (status) { return status <= 400; } }).then(function (response) {
                    if (response.status == 200) {
                        //console.log('Smazano z kosiku (prihlaseny uzivatel): ', response.data);
                    }
                }).catch(function (e) {
                    console.log(e);
                    _this.setState(__assign({}, _this.state));
                });
            }
            else {
                (0, localStorageService_1.DeleteCartItem)(cartItem);
            }
            var filteredCartItems = cartItems.filter(function (i) { return i.productID !== productId; });
            _this.setState({ cartItems: filteredCartItems, cartItemsCount: filteredCartItems.length });
        };
        // Removes one amount of an item in the shopping cart or deletes it if the amount is <= 0
        _this.handleRemoveFromCart = function (productId, amount) {
            var cartItems = __spreadArray([], _this.state.cartItems, true); // copy of state array (we don't want to change directly the state array)
            var cartItem = {
                productID: productId,
                amount: amount // amount should be always 1
            };
            var item = cartItems.find(function (i) { return i.productID === productId; });
            if (item !== undefined) { // if the item is in the shopping cart
                if ((item.amount - amount) <= 0) { // delete product
                    _this.handleDeleteFromCart(productId);
                }
                else { // remove one amount
                    var user = (0, localStorageService_1.GetObject)();
                    if (user !== null) {
                        httpService_1.default.post((0, routes_1.OrderController_RemoveOrderItem)(user.unique_name.toString()), cartItem, { validateStatus: function (status) { return status <= 400; } }).then(function (response) {
                            if (response.status == 200) {
                                //console.log('Snizeno mnozstvi produktu v kosiku (prihlaseny uzivatel): ', response.data);
                                //this.setState({ cartItemsCount: response.data.amount }); // only amount changed so no need to update cartItemsCount
                            }
                        }).catch(function (e) {
                            console.log(e);
                            _this.setState(__assign({}, _this.state));
                        });
                    }
                    else {
                        (0, localStorageService_1.DecreaseCartItemAmount)(cartItem); // change amount of item in local storage
                        //console.log("Zmenen pocet kusu v local storage (neprihlaseny uzivatel)");
                    }
                    var index = cartItems.indexOf(item); // find his index
                    cartItems[index] = __assign({}, item); // make copy of item object
                    cartItems[index].amount -= amount; // change the amount
                    _this.setState({ cartItems: cartItems }); // save new array
                    //console.log("Odecteno mnozstvi produktu, ktery je jiz v kosiku (snizil se pouze pocet kusu v kosiku)");
                }
            }
        };
        _this.handleSearchClick = function (searchString) {
            _this.setState({ searchString: searchString });
            if (_this.props.history.location.pathname !== '/') {
                _this.props.history.push('/');
            }
        };
        // Sets authorization token to the local storage and axios header
        _this.handleLoginClick = function (values) {
            httpService_1.default.post(routes_1.AccountController_AuthenticateUser, values, { validateStatus: function (status) { return status <= 400; } }).then(function (response) {
                if (response.status == 200) {
                    (0, localStorageService_1.SetAuthorizationTokenLocalStorage)(response.data);
                    var user = (0, localStorageService_1.GetObject)();
                    if (user !== null) {
                        _this.getUserShoppingCart(user);
                    }
                    _this.props.history.push("/");
                }
                else if (response.status == 400) {
                    _this.setState({ displayErrorMessage: true });
                }
            }).catch(function (e) {
                console.log(e);
                _this.setState(__assign({}, _this.state));
            });
        };
        // Deletes authorization token from the local storage and axios header
        _this.handleLogoutClick = function (e) {
            (0, localStorageService_1.DeleteAuthorizationToken)();
            _this.getAnonymousShoppingCart();
            _this.props.history.push('/login');
        };
        _this.handleClearShoppingCart = function () {
            _this.setState({ cartItemsCount: 0, cartItems: new Array() });
        };
        return _this;
    }
    // If user is logged in, then get his shopping cart items, else try to load cart items from the local storage
    UserRoutes.prototype.componentDidMount = function () {
        return __awaiter(this, void 0, void 0, function () {
            var user;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        user = (0, localStorageService_1.GetObject)();
                        if (!(user !== null)) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.getUserShoppingCart(user)];
                    case 1:
                        _a.sent();
                        return [3 /*break*/, 4];
                    case 2: return [4 /*yield*/, this.getAnonymousShoppingCart()];
                    case 3:
                        _a.sent();
                        _a.label = 4;
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    UserRoutes.prototype.getAnonymousShoppingCart = function () {
        return __awaiter(this, void 0, void 0, function () {
            var storageCartItems, cartItems;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        storageCartItems = (0, localStorageService_1.GetShoppingCart)();
                        cartItems = [];
                        if (!(storageCartItems.length > 0)) return [3 /*break*/, 2];
                        return [4 /*yield*/, Promise.all(storageCartItems.map(function (i) { return __awaiter(_this, void 0, void 0, function () {
                                var _this = this;
                                return __generator(this, function (_a) {
                                    switch (_a.label) {
                                        case 0: return [4 /*yield*/, httpService_1.default.get((0, routes_1.ProductController_GetProduct)(i.productID.toString())).then(function (response) { return __awaiter(_this, void 0, void 0, function () {
                                                var product, cartItem;
                                                return __generator(this, function (_a) {
                                                    switch (_a.label) {
                                                        case 0: return [4 /*yield*/, response.data];
                                                        case 1:
                                                            product = _a.sent();
                                                            cartItem = {
                                                                id: 0,
                                                                productID: product.id,
                                                                name: product.name,
                                                                price: (product.reducedPrice != undefined && product.reducedPrice > 0 && product.reducedPrice < product.price) ? product.reducedPrice : product.price,
                                                                amount: i.amount,
                                                                availableQuantity: product.availableQuantity,
                                                                productCategoryID: product.productCategoryID,
                                                                productCategoryName: product.productCategoryName,
                                                                productImageID: product.productImageIDs[0]
                                                            };
                                                            cartItems.push(cartItem);
                                                            return [2 /*return*/];
                                                    }
                                                });
                                            }); })
                                                .catch(function (e) {
                                                console.log(e);
                                                _this.setState(__assign({}, _this.state));
                                            })];
                                        case 1:
                                            _a.sent();
                                            return [2 /*return*/];
                                    }
                                });
                            }); }))];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2:
                        this.setState({ cartItems: cartItems, cartItemsCount: storageCartItems.length, userName: '' });
                        return [2 /*return*/];
                }
            });
        });
    };
    UserRoutes.prototype.render = function () {
        var _this = this;
        var _a = this.state, cartItems = _a.cartItems, cartItemsCount = _a.cartItemsCount, displayErrorMessage = _a.displayErrorMessage, searchString = _a.searchString, userName = _a.userName;
        cartItems.sort(function (a, b) { return a.name < b.name ? -1 : 1; });
        return (React.createElement(userLayout_1.default, { cartItemsAmount: cartItemsCount, onLogoutClick: this.handleLogoutClick, onSearchClick: this.handleSearchClick, userName: userName },
            React.createElement(react_router_1.Route, { exact: true, path: "/", render: function () { return React.createElement(productList_1.default, { onAddToCartClick: _this.handleAddToCart, searchString: searchString }); } }),
            React.createElement(react_router_1.Route, { path: "/aboutus", render: function () { return React.createElement(AboutUs_1.default, null); } }),
            React.createElement(react_router_1.Route, { path: "/account" }, (0, localStorageService_1.IsCustomerLoggedIn)()
                ? React.createElement(AccountHeader_1.AccountHeader, null,
                    React.createElement(react_router_1.Route, { path: "/account/info", component: AccountInfo_1.default }),
                    React.createElement(react_router_1.Route, { path: "/account/addresses", component: AddressManagement_1.default }),
                    React.createElement(react_router_1.Route, { path: "/account/order/:id", render: function (props) {
                            return React.createElement(OrderDetail_1.default, __assign({}, props));
                        } }),
                    React.createElement(react_router_1.Route, { path: "/account/orders", component: OrderList_1.default }),
                    React.createElement(react_router_1.Route, { path: "/account/passwordChange", component: ChangePasswordForm_1.default }))
                : React.createElement(react_router_1.Redirect, { to: "/login" })),
            React.createElement(react_router_1.Route, { path: "/cart", render: function (props) {
                    return React.createElement(shoppingCart_1.default, __assign({}, props, { cartItems: cartItems, onAddToCartClick: _this.handleAddToCart, onDeleteFromCartClick: _this.handleDeleteFromCart, onRemoveFromCartClick: _this.handleRemoveFromCart }));
                } }),
            React.createElement(react_router_1.Route, { path: "/contacts", render: function () { return React.createElement(Contacts_1.default, null); } }),
            React.createElement(react_router_1.Route, { path: "/checkout", component: function (props) {
                    return React.createElement(checkout_1.default, __assign({}, props, { getUserShoppingCart: _this.getUserShoppingCart, clearShoppingCart: _this.handleClearShoppingCart }));
                } }),
            React.createElement(react_router_1.Route, { path: "/delivery", render: function () { return React.createElement(Delivery_1.default, null); } }),
            React.createElement(react_router_1.Route, { path: "/tradeterms", render: function () { return React.createElement(TradeTerms_1.default, null); } }),
            React.createElement(react_router_1.Route, { path: "/login", render: function (props) {
                    if ((0, localStorageService_1.IsCustomerLoggedIn)()) {
                        return React.createElement(react_router_1.Redirect, { to: "/" });
                    }
                    else {
                        return React.createElement(Login_1.default, __assign({}, props, { displayErrorMessage: displayErrorMessage, onSubmitClick: _this.handleLoginClick }));
                    }
                } }),
            React.createElement(react_router_1.Route, { path: "/order/successful", render: function (props) { return React.createElement(OrderCompleted_1.default, __assign({}, props, { clearShoppingCart: _this.handleClearShoppingCart })); } }),
            React.createElement(react_router_1.Route, { path: "/passwordRecovery", render: function (props) { return React.createElement(PasswordRecovery_1.PasswordRecovery, __assign({}, props)); } }),
            React.createElement(react_router_1.Route, { path: "/passwordReset/:token", component: PasswordReset_1.default }),
            React.createElement(react_router_1.Route, { path: "/product/:id", render: function (props) {
                    return React.createElement(productDetail_1.default, __assign({}, props, { onAddToCartClick: _this.handleAddToCart }));
                } }),
            React.createElement(react_router_1.Route, { path: "/signup", component: function (props) { return React.createElement(Signup_1.default, __assign({}, props)); } })));
    };
    return UserRoutes;
}(React.Component));
exports.default = UserRoutes;
//# sourceMappingURL=userRoutes.js.map