/**
 *
 * Example usage for the cart or clipboard item count.
 * <span data-tportal-count-link="client_name" data-tportal-count-type="[cart or clipboard]" data-content="0"></span>
 *
 */
export class TportalCountLink {

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

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

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

        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();

            switch (this.type) {
                case 'cart':
                    if (body && body.cart > 0) {
                        this.setItemCount(body.cart);
                    }
                    break;
                case 'clipboard':
                    if (body && body.clipboard > 0) {
                        this.setItemCount(body.clipboard);
                    }
                    break;
            }

        } else {
            console.warn(`Can't fetch TPortal itemcount. 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;
        }
    }
}
