import { getCookie, setCookie } from "../lib/cookie.js"
import { Controller } from "../stimulus.js"

export default class extends Controller {
    static get targets() {
        return [ "cartList" ]
    }

    connect() {
        console.log(getCookie('cart'))
        this.cart = this.getOrSetCart()
        this.element.addEventListener('addToCart', this.addItem.bind(this))
    }

    getOrSetCart() {
        let cart = JSON.parse(getCookie('cart'))
        if (cart === null) {
            console.log('created cart cookie')
            setCookie('cart', '{}')
            cart = {}
        } else {
            Object.keys(cart).forEach((item_id) => {
                fetch(`/${item_id}/`)
                .then((response) => response.text())
                .then((html) => {
                    this.cartListTarget.innerHTML += html;
                });
            })
        }
        return cart
    }

    decodeCartItems(cart) {

    }

    addItem(event) {
        if (this.cart[event.detail.item] === undefined) {
            this.cart[event.detail.item] = {'quantity': 1}
        } else {
            this.cart[event.detail.item]['quantity'] += 1
        }
        setCookie('cart', JSON.stringify(this.cart))
        console.log(this.cart)

        fetch(`/${event.detail.item}/`)
        .then((response) => response.text())
        .then((html) => {
            this.cartListTarget.innerHTML += html;
        });
    }

    removeItem() {

    }

    refresh() {
        
    }
}