import { Component, Method, Listen, EventEmitter, Event, h } from '@stencil/core';
import { createPopper } from '@popperjs/core';

@Component({
    tag: 'tooltip-confirm-delete',
    styleUrl: 'tooltip-confirm-delete.css',
    scoped: true,
})
export class TooltipConfirmDelete {
    @Event() confirmDelete: EventEmitter;
    tooltip: HTMLElement;

    @Method()
    async init(removeEl: HTMLElement) {
        // show a prompt

        createPopper(removeEl, this.tooltip, {
            placement: 'top',
        });

        this.tooltip.setAttribute('data-show', '');
    }

    @Listen('click', { capture: true, target: 'window' })
    clickHandler(event) {
        if (event.target != this.tooltip) {
            this.tooltip.removeAttribute('data-show');
        }
    }

    @Listen('touchstart', { capture: true, target: 'window' })
    touchstartHandler(event) {
        const touch = event.changedTouches[0];
        if (!this.tooltip.contains(touch.target)) {
            this.tooltip.removeAttribute('data-show');
        }
    }

    cancelDeleteHandler() {
        this.tooltip.removeAttribute('data-show');
    }

    render() {
        return (
            <span class="tooltip" ref={el => (this.tooltip = el as HTMLElement)}>
                Are you sure?
                <button class="yes" onClick={() => this.confirmDelete.emit()}>
                    Remove
                </button>
                <button class="no" onClick={this.cancelDeleteHandler.bind(this)}>
                    Cancel
                </button>
                <div class="tooltip-arrow" data-popper-arrow></div>
            </span>
        );
    }
}
