'use strict';

import {Controller} from 'stimulus';
import {getComponent} from '@symfony/ux-live-component';

export default class extends Controller {
    async initialize() {
        window.dispatchEvent(new CustomEvent('reset-media-selection'));
        this.component = await getComponent(this.element.closest('[data-controller~="live"]'));
        this.component.on('model:set', async (model, value, component) => {
            const input = this.element.querySelector(
                `[data-model="${model.replace(/\./g, '_')}"][data-action]`
            );
            if (input) {
                if (input?.files?.length > 0) {
                    this.component.files(input.getAttribute('name'), input);
                    //await this.component.action(input.getAttribute('data-action'));
                }
            }
        });
        window.addEventListener('preview:image', (e) => {
            const containerId = 'preview-' + e.detail.id.replace(/\./g, '_');
            const previewContainer = this.element.querySelector('#' + containerId);
            if (!this.element.contains(previewContainer)) {
                return;
            }
            const id = e.detail.id;
            const path = e.detail.path;
            const url = e.detail.url;
            const previewImage = previewContainer.querySelector('div[data-preview] img');
            const buttonDelete = previewContainer.querySelector('div[data-preview] button');
            if (buttonDelete) {
                buttonDelete.setAttribute('data-live-field-name-param', id);
                buttonDelete.setAttribute('data-live-path-param', path);
            }

            previewImage.src = url;
            previewContainer.classList.add('preview');
        });

        window.addEventListener('preview:remove', (e) => {
            const containerId = 'preview-' + e.detail.id.replace(/\./g, '_');
            const previewContainer = this.element.querySelector('#' + containerId);
            if (!this.element.contains(previewContainer)) {
                return;
            }
            const previewImage = previewContainer.querySelector('div[data-preview] img');
            const buttonDelete = previewContainer.querySelector('div[data-preview] button');
            if (buttonDelete) {
                buttonDelete.setAttribute('data-live-field-name-param', null);
                buttonDelete.setAttribute('data-live-path-param', null);
            }
            previewImage.removeAttribute('src');
            previewContainer.classList.remove('preview');
        });
    }
}
