import { Controller } from '@hotwired/stimulus';

/**
 * Show warning before deleting record
 * [template: {entity}/index.html.twig]
 */
export default class extends Controller {
    static targets = ['modal', 'path', 'name', 'message'];

    /**
     * @todo Refactor with actions for modal
     * @param {object} event 
     */
    warn(event) {
        event.preventDefault();
        const id = event.currentTarget.getAttribute('data-url').match(/\d+$/)[0];
        const modal = this.modalTarget;
        let name = '';
        // For record list in landing pages
        if (this.nameTargets.length > 1) {
            name = this.nameTargets.find(a => a.href.includes(id)).textContent;
        } else {
            name = this.nameTarget.textContent;
        }

        const message = `The record '<strong>${name.trim()}</strong>' will be permanently deleted. Proceed?`;

        modal.classList.add('is-active');
        this.messageTarget.innerHTML = message;
        modal.querySelector('.delete').addEventListener('click', () => {
            modal.classList.remove('is-active');
        });
        modal.querySelector('.modal-background').addEventListener('click', () => {
            modal.classList.remove('is-active');
        });
        modal.querySelector('#cancel').addEventListener('click', () => {
            modal.classList.remove('is-active');
        });

    }
    // Proceed with deletion...
    delete() {
        const delPath = this.pathTarget.getAttribute('data-url');
        location.href = delPath;
    }
}
