import { url } from '../utils.js';

let isSync = false;
let items = null;

export async function sync() {
    if (!isSync) {
        if (items !== null) {
            let miniItems = items.map(obj => { return { id: obj.id, quantity: obj.quantity } });
            localStorage.setItem("cart", JSON.stringify(miniItems));
        }

        if (localStorage.getItem("cart") != null) {
            let cartItems = localStorage.getItem("cart");
            items = JSON.parse(cartItems);
        }

        let ids = items.map(obj => obj.id);

        if (ids.length > 0) {
            let products = await fetch(url("/contents/" + ids.join(",")));
            products = await products.json();

            products.contents.forEach(product => {
                product.quantity = items.find(obj => obj.id == product.id).quantity;

                product.calc_preis = product.preis;
                if (product.quantity >= 5 && product.preis_5) product.calc_preis = product.preis_5;
                if (product.quantity >= 10 && product.preis_10) product.calc_preis = product.preis_10;
            });

            items = products.contents;
        }

        isSync = true;
    }
}

export function addItem(id) {
    let objProductInfo = items.find(obj => obj.id == id);
    let index = items.indexOf(objProductInfo);
    if (index == -1) items.push({ id: id, quantity: 1 });
    isSync = false;
    sync();
}

export async function updateItem(id, data) {
    let product = await getItem(id);
    if (data.quantity) product.quantity = data.quantity;
    isSync = false;
    await sync();
}

export async function removeItem(id) {
    items = items.filter(item => item.id !== Number(id));
    console.log(items);
    isSync = false;
    await sync();
}

export async function getItem(id) {
    await sync();
    return items.find(obj => obj.id == id);
}

export async function getItems() {
    await sync();
    return items;
}

export async function getQuantity() {
    await sync();
    let quantitys = items.map(obj => obj.quantity);
    let quantityOfProducts = 0;
    for (let i = 0; i < quantitys.length; i++) { if (Number.isInteger(Number(quantitys[i]))) quantityOfProducts += Number(quantitys[i]); }
    return quantityOfProducts;
}

export async function getTotalPrice() {
    await sync();

    let totalPrice = 0;

    items.forEach(product => {
        product.calc_preis = product.preis;
        if (product.quantity >= 5 && product.preis_5) product.calc_preis = product.preis_5;
        if (product.quantity >= 10 && product.preis_10) product.calc_preis = product.preis_10;
        totalPrice += product.calc_preis * product.quantity;
    });

    return totalPrice;
}

export async function getLink() {
    await sync();
    let miniItems = items.map(obj => { return { id: obj.id, quantity: obj.quantity } });
    return url("/?cart=" + btoa(JSON.stringify(miniItems)));
}