import { loadOutdoorActive, onOutdoorActiveLoadingError } from './outdoor-active-api';

/**
 * Initializes a outdooractive pdf download button.
 * If loading the outdooractive SDK fails the button is being hidden.
 */
export class OutdoorActivePdfDownload {

    constructor (node, outdoorActiveId) {

        /** @private {HTMLElement} */
        this.node = node;

        /** @private {string} */
        this.outdoorActiveId = outdoorActiveId;
        this.node.addEventListener('click', e => {
            e.preventDefault();
            this.onNodeClick();
        });

        onOutdoorActiveLoadingError(() => {
            if (this.node.parentNode) {
                this.node.parentNode.removeChild(this.node);
                console.warn('Removing outdoor active PDF download button: Error loading outdooractive sdk');
            }
        });
    }

    async onNodeClick() {
        const oax = await loadOutdoorActive();

        /*
         * The outdooractive SDK assumes that it is loaded upfront and listens for clicks
         * on the event. In order to make lazily-loading the SDK work we create an empty
         * div on which a click is mocked.
         */
        const mockElement = document.createElement('div');
        oax.pdfDialog(this.outdoorActiveId, mockElement);
        mockElement.click();
    }

}
