<repo_name>Blednykh/focusStartProject<file_sep>/app/js/renderBasketModule.js
function renderBasketTableContent(table, basket) {
    let {goodsList} = basket;
    if (goodsList !== null && goodsList.length !== 0) {
        goodsList.forEach(item => {
            let temp = document.getElementById("temp_type_basket-item");

            let clon = temp.content.cloneNode(true);

            let productImg = clon.querySelector(".product__img");

            productImg.src = item.img;

            let descriptionProductName = clon.querySelector(".description__product-name");

            descriptionProductName.innerText = item.prod;

            let descriptionSupplierName = clon.querySelector(".description__supplier-name");

            descriptionSupplierName.innerText = item.supp;

            let basketItemPrice = clon.querySelector(".basket-item__price");

            basketItemPrice.innerText = `$${parseFloat(item.price).toFixed(3)}`;

            let basketItemInput = clon.querySelector(".basket-item__input");

            basketItemInput.placeholder = item.count;

            let basketItemTotalPrice = clon.querySelector(".basket-item__total-price");
            basketItemTotalPrice.innerText = "$" + (parseFloat(item.price) * item.count).toFixed(2);

            basketItemInput.addEventListener("keyup", (e) => {
                if (Object.is(parseInt(basketItemInput.value), NaN)) {
                    basketItemInput.value = "";
                } else {
                    if (parseInt(basketItemInput.value) === 0) {
                        let basketItems = document.querySelectorAll(".basket__basket-item");

                        basket.removeGoods(item);
                        basketItems.forEach(item => item.remove());
                        renderBasketTableContent(table, basket);
                    } else {
                        basket.changeItemCount(item, basketItemInput.value);
                        basketItemTotalPrice.innerText = "$" + (item.price * basketItemInput.value).toFixed(3);
                        basketItemInput.placeholder = basketItemInput.value;
                    }
                    renderTotalPrice(basket.sum)
                }
            });

            //Удаление из корзины
            let productLogoCross = clon.querySelector(".product__logo-cross");
            productLogoCross.addEventListener("click", () => {
                basket.removeGoods(item);

                let basketItems = document.querySelectorAll(".basket__basket-item");

                basketItems.forEach(item => item.remove());
                renderBasketTableContent(table, basket);
                renderTotalPrice(basket.sum)
            });
            
            table.appendChild(clon);
        })
    }
    else {
        //Пустая корзина
        let totalPriceBoxPrice = document.querySelector(".total-price-box__price");

        let totalPriceBoxButton = document.querySelector(".total-price-box__button");

        totalPriceBoxPrice.innerText = "$0.00";
        totalPriceBoxButton.disabled = true;

        let h2 = document.createElement("h2");

        h2.innerText = "No Goods in Cart!";
        table.replaceWith(h2);
    }
}
//рендер подтабличных данных
function renderTotalPrice(sum) {
    let mainElement = document.querySelector(".l-main");

    let priceCount = mainElement.querySelector(".price__count");

    let priceItem = priceCount.querySelector(".price__item");

    priceItem.innerText = "$" + Math.round(parseFloat(sum) * 10 * 10) / 100;

    let totalPriceBoxPrice = mainElement.querySelector(".total-price-box__price");

    totalPriceBoxPrice.innerText = "$" + Math.round((parseFloat(sum) + 5) * 10 * 10) / 100;
}

export function renderBasket(basket) {
    let mainElement = document.querySelector(".l-main");

    let mainContent = mainElement.querySelector(".l-main-content");

    mainElement.removeChild(mainContent);
    mainElement.className = `l-main main_type_basket`;

    let temp = document.getElementById("temp_type_basket");

    let basketClon = temp.content.cloneNode(true);

    mainElement.appendChild(basketClon);

    let table = mainElement.querySelector(".basket__basket-table");

    renderTotalPrice(basket.sum);
    renderBasketTableContent(table, basket);
}<file_sep>/app/js/setHomeContentModule.js
import {sendRequest} from "./apiModule.js";

const HOME_ITEMS_URL_LIST = [
    "http://localhost:3000/data/home-items/homeItemsA.json",
    "http://localhost:3000/data/home-items/homeItemsB.json"
];

function createMenuItem(basket, marketItem, priority, size) {
    let temp = document.getElementById("temp_type_home-item");

    let clone = temp.content.cloneNode(true);

    let section = clone.querySelector(".c-menu-item");

    let img = clone.querySelector(".c-menu-item__img");

    let supp = clone.querySelector(".c-menu-item__supp");

    let prod = clone.querySelector(".c-menu-item__prod");

    let price = clone.querySelector(".c-menu-item__price");

    let svg = clone.querySelector(".c-menu-item__logo");

    section.className = "c-menu-item";
    section.className += (priority === "top") ? " home-menu-top-item" : " home-menu-bottom-item";
    section.className += (size === "large") ? " t-size-large" : "";

    img.className = "c-menu-item__img";
    img.src = marketItem.img;

    supp.innerText = marketItem.supp;
    prod.innerText = marketItem.prod;
    price.innerText = "$" + marketItem.price;

    svg.addEventListener("click", () => {
        basket.addGood(marketItem);
    });

    return clone;
}


export function setHomeContent(menuTopElements, menuBottomLeftElements, menuBottomRightElements, basket) {

    let url = HOME_ITEMS_URL_LIST[Math.floor(Math.random() * HOME_ITEMS_URL_LIST.length)];

    sendRequest('GET', url)
        .then(response => {
            let marketItems = response;

            marketItems
                .filter(item => item.type === "top")
                .forEach(item => {
                    menuTopElements.appendChild(createMenuItem(basket, item, "top"))
                });

            marketItems
                .filter(item => {
                    return item.type !== "top"
                }).forEach((item, i) => {
                if (i === 0) {
                    menuBottomLeftElements.appendChild(createMenuItem(basket, item, "", "large"));
                    return;
                }
                if (i === 9) {
                    menuBottomRightElements.appendChild(createMenuItem(basket, item, "", "large"));
                    return;
                }
                if (i % 2 === 0) {
                    menuBottomLeftElements.appendChild(createMenuItem(basket, item));
                } else {
                    menuBottomRightElements.appendChild(createMenuItem(basket, item));
                }
            });
        });

}<file_sep>/app/js/renderSubcategoryPageModule.js
import {sendRequest} from "./apiModule.js";

function renderPage(basket, title, item) {
    let pathItem = document.querySelectorAll(".o-path__item");

    pathItem[0].innerText = title;
    pathItem[1].innerText = item;

    let h2 = document.querySelector(".main_type_menu__h2");

    h2.innerText = item;

    let pathPart = item.split(" ").join("-").toLowerCase();

    let HOME_SUB_URL_LIST = [
        `http://localhost:3000/data/subcategory-items/${pathPart}/${pathPart}ItemsA.json`,
        `http://localhost:3000/data/subcategory-items/${pathPart}/${pathPart}ItemsB.json`
    ];

    let url = HOME_SUB_URL_LIST[Math.floor(Math.random() * HOME_SUB_URL_LIST.length)];

    sendRequest('GET', url)
        .then(response => {
            let marketItem = response;

            let menuBox = document.querySelector(".menu-box");

            marketItem
                .forEach(item => {
                    let temp = document.getElementById("temp_type_subcategory-list");

                    let clon = temp.content.cloneNode(true);

                    let productImg = clon.querySelector(".c-menu-item__img");

                    productImg.src = item.img;

                    let productName = clon.querySelector(".c-menu-item__prod");

                    productName.innerText = item.prod;

                    let supplierName = clon.querySelector(".c-menu-item__supp");

                    supplierName.innerText = item.supp;

                    let productPice = clon.querySelector(".c-menu-item__price");

                    productPice.innerText = `$${item.price}`;

                    let svg = clon.querySelector(".o-shape-logo");

                    svg.addEventListener("click", () => {
                        basket.addGood(item);
                    });
                    menuBox.appendChild(clon);

                });
        })
}

export function renderSubcategoryPage(basket, title, item) {
    let mainElement = document.querySelector(".l-main");

    let mainContent = mainElement.querySelector(".l-main-content");

    mainElement.removeChild(mainContent);
    mainElement.className = `l-main main_type_menu`;

    let temp = document.getElementById("temp_type_subcategory");

    let pageClon = temp.content.cloneNode(true);

    mainElement.appendChild(pageClon);
    renderPage(basket, title, item);
}<file_sep>/app/js/script.js
import {setHeaderSubcategoriesContent} from "./setHeaderSubcategoriesContentModule.js";
import {sendRequest} from "./apiModule.js";
import {Basket} from "./Basket.js";
import {createBasketBox} from "./basketBoxCreateModule.js";
import {renderHome} from "./renderHomeModule.js";
import {renderBasket} from "./renderBasketModule.js";
import {renderOrderAddress} from "./renderOrderAddressModule.js";
import {renderOrderPayment} from "./renderOrderPaymentModule.js";
import {renderOrderEnd} from "./renderOrderEndModule.js";
import {Address} from "./Address.js";
import {Router} from "./Router.js";
import {renderSubcategoryPage} from "./renderSubcategoryPageModule.js";

//Инициализация роутинга
let router = new Router();

//Инициализация корзины
let basket = new Basket();

//Инициализация объекта с данными об адресе покупателя
let address = new Address();

//Заполнение мини-корзины в шапке
createBasketBox(basket);

//Создание подкатегорий в шапке
let categoryListLi = document.querySelectorAll(".category-list__li");

sendRequest('GET', "http://localhost:3000/data/goods-categories/categories.json")
    .then(response => {
        let HeaderBottomItems = response;

        categoryListLi.forEach((item, i) => setHeaderSubcategoriesContent(item, i, HeaderBottomItems, basket, router));
    });


//Рендер необходимой страницы
locationHashChanged();

function locationHashChanged() {
    switch (location.hash) {
        case "#basket": {
            renderBasket(basket, address);
            break;
        }
        case  "": {
            renderHome(basket);
            break;
        }
        case "#order-address": {
            renderOrderAddress(basket, address);
            break;
        }
        case "#order-payment": {
            renderOrderPayment(basket, address);
            break;
        }
        case "#order-end": {
            renderOrderEnd();
            break;
        }
        default: {
            let findOpenedSubcategoryIndex = router.findIndexByHash(location.hash);

            if (findOpenedSubcategoryIndex !== -1) {
                renderSubcategoryPage(
                    basket,
                    router.subcategoryData[findOpenedSubcategoryIndex].title,
                    router.subcategoryData[findOpenedSubcategoryIndex].subcategoryItem
                );
            } else {
                location.href = "";
            }

        }

    }

}

window.onhashchange = locationHashChanged;<file_sep>/app/js/setHeaderSubcategoriesContentModule.js
import {sendRequest} from "./apiModule.js";

export function setHeaderSubcategoriesContent(element, number, HeaderBottomItems, basket, router) {

    let title, losung, count, subcategoriesList;

    let temp = document.getElementById("temp_type_nav-item-container");

    let clon = temp.content.cloneNode(true);

    element.appendChild(clon);

    let h1__title = element.querySelector(".nav-item-container__title");

    h1__title.innerText = "Loading...";

    let categoriesListItem = element.querySelector(".categories-list__item");

    element.addEventListener("mouseover", (e) => {
        if (e.target === element || e.target === categoriesListItem) {
            let pathPart = HeaderBottomItems[number].split(" ").join("-").toLowerCase();

            sendRequest('GET', `http://localhost:3000/data/goods-categories/${pathPart}.json`)
                .then(response => {
                    title = response.title;
                    losung = response.losung;
                    count = response.count;
                    subcategoriesList = response.subcategoriesList;

                    let navItemContainerContent = element.querySelector(".nav-item-container__content");

                    navItemContainerContent.remove();
                    navItemContainerContent = document.createElement("div");
                    navItemContainerContent.className = "nav-item-container__content subcategories-list";

                    let el = element.querySelector(".nav-item-container");

                    let h1__title = element.querySelector(".nav-item-container__title");

                    h1__title.innerText = title;

                    let h1__losung = element.querySelector(".nav-item-container__losung");

                    h1__losung.innerText = losung;

                    let p = element.querySelector(".nav-item-container__count");

                    p.innerText = count + " items";

                    subcategoriesList.forEach(column => {
                        let ul = document.createElement("ul");

                        ul.className = "subcategories-list__column";
                        column.forEach(item => {

                            let li = document.createElement("li");

                            let a = document.createElement("a");

                            li.className = "subcategories-list__li";
                            a.innerText = item;
                            a.href = `#${item.replace(/\s+/g, '')}`;
                            li.appendChild(a);
                            ul.appendChild(li);

                            li.addEventListener("click", () => {
                                router.addHash(title, item);
                            })
                        });
                        navItemContainerContent.appendChild(ul);
                    });

                    el.appendChild(navItemContainerContent);
                });
        }
    });

}<file_sep>/app/js/apiModule.js
export function sendRequest(method, url) {
    return new Promise((resolve, reject) => {
        let xhr = new XMLHttpRequest();

        xhr.open(method, url);

        xhr.onload = function () {
            resolve((JSON.parse(xhr.responseText)));
        };
        xhr.onerror = function (e) {
            console.log("xhr-status", xhr.statusText, this.status);
            reject(this.status);
        };
        xhr.readystatechange = function (e) {
            console.log("target", e.target);
            console.log("readyState", xhr.readyState);
        };
        xhr.send();
    });
}<file_sep>/app/js/Address.js
export class Address {
    constructor() {
        this.firstName = "";
        this.lastName = "";
        this.companyName = "";
        this.country = "";
        this.town = "";
        this.postcode = "";
        this.address = "";
        this.email = "";
        this.phone = "";
    }

    getAddress() {
        return {
            firstName: this.firstName,
            lastName: this.lastName,
            companyName: this.companyName,
            country: this.country,
            town: this.town,
            postcode: this.postcode,
            address: this.address,
            email: this.email,
            phone: this.phone
        }
    }
}<file_sep>/app/js/Basket.js
export class Basket {
    constructor() {
        let localStorageSum = localStorage.getItem("sum");

        let localStorageGoodsList = JSON.parse(localStorage.getItem("goodsList"));

        this.sum = localStorageSum === null ? 0 : parseFloat(localStorageSum);
        this.goodsList = localStorageGoodsList === null ? [] : localStorageGoodsList;
    }

    addGood(goods) {
        this.sum += parseFloat(goods.price);

        let findIndex = this.goodsList.findIndex(item => item.id === goods.id);

        if (findIndex !== -1) {
            this.goodsList[findIndex].count++;
        } else {
            this.goodsList.push({...goods, count: 1});
        }
        this.writeToLocalStorage()
    }

    removeGoods(goods) {
        this.sum = parseFloat((this.sum - goods.price * goods.count).toFixed(2));
        this.goodsList = this.goodsList.filter(item => item.id !== goods.id);
        this.writeToLocalStorage()
    }

    getCount() {
        return this.goodsList.reduce((prev, item) => prev + item.count, 0);
    }

    getBasket() {
        return {
            sum: this.sum,
            goodsList: this.goodsList
        }
    }

    changeItemCount(goods, newCount) {
        if(!isNaN(newCount)){
            let changeItemId = this.goodsList.findIndex(item => item.id === goods.id);

            this.sum = Number((this.sum - goods.price * goods.count).toFixed(2));
            this.goodsList[changeItemId].count = parseInt(newCount);
            this.sum += Number((goods.price * newCount).toFixed(5));

            this.writeToLocalStorage()
        }
    }

    clear() {
        this.sum = 0;
        this.goodsList = [];
        this.writeToLocalStorage()
    }

    writeToLocalStorage() {
        localStorage.setItem("sum", this.sum);
        localStorage.setItem("goodsList", JSON.stringify(this.goodsList));
    }

 /*   equal(goodsList){
        return goodsList.length === this.goodsList.length && goodsList.every((item,i)=>{
            return item === this.goodsList[i] && item.count === this.goodsList[i].count;
        });
    }*/
}