/**
 *
 * Example usage for the shopping cart item count.
 * <span data-tportal-shoppingcart-count="client_name" data-content="0"></span>
 *
 */
export class TportalShoppingcart {

    /**
     * @param {HTMLElement} element
     */
    constructor (element) {
        /** @private {HTMLElement} */
        this.element = element;

        /** @private {string} */
        this.client = element.getAttribute('data-tportal-shoppingcart-count');

        this.fetch();
    }

    async fetch () {
        const response = await fetch(`${window.location.origin}/${this.client}/itemcount`,{
            credentials: 'same-origin',
            headers: {
                'Content-Type': '*/*',
            },
        });

        if (response.ok) {
            const body = await response.json();

            if (body && body.cart > 0) {
                this.setItemCount(body.cart);
            }
        } else {
            console.warn(`Can't fetch TPortal shopping cart. HTTP-Error: ${  response.status  } Item count set to 0`);
            this.setItemCount('0');
        }
    }

    setItemCount (count) {
        if (this.element.hasAttribute('data-content')) {
            this.element.setAttribute('data-content', `${count}`);
        } else {
            this.element.innerHTML = count;
        }
    }

}
