// Global ATON
import { Controller } from "@hotwired/stimulus"
import AppState from "../state.js";
import { addClippingPlane, resetClipping } from "../utils/clipping.js";
import { toggleAmbientOcclusion } from "../utils/environment.js";

/**
 * Handle events for the clipper toolbar,
 * related to the clipping module
 */
export default class extends Controller {
    static targets = ['trigger', 'clipper', 'axis'];
    static values = { enabled: Boolean };

    connect() {
        console.log('#clipper controller connected');
    }

    clip(event) {
        /**
         * @type {string}
         */
        const label = event.params.axis;
        /**
         * @type {HTMLButtonElement}
         */
        const target = event.target;
        /**
         * @type {NodeListOf<HTMLButtonElement>}
         */
        const axes = this.axisTargets;
        const classes = ['border', 'border-2', 'border-warning'];

        addClippingPlane(label, -1);
        target.classList.add(...classes);

        for (const btn of axes) {
            if (btn.id !== target.id) {
                btn.classList.remove(...classes);
            }
        }
    }
    /**
     * Toggle clipper toolbar
     */
    toggleClipper() {
        /**
         * @type {HTMLElement}
         */
        const trigger = this.triggerTarget;
        this.clipperTarget.classList.toggle('d-none');
        // If the toolbar is shown, clipping is enabled and vice versa
        this.enabledValue = !this.clipperTarget.classList.contains('d-none');

        this.axisTargets.forEach(btn => {
            btn.classList.remove('border', 'border-2', 'border-warning');
        });

        if (this.enabledValue) {
            // AO should be turned off if clipping is enabled
            toggleAmbientOcclusion(false);
            trigger.className += ' border border-2 border-white';
        }

        if (!this.enabledValue) {
            resetClipping();
            trigger.className = trigger.className.replace(/ border.*$/g, '');
            toggleAmbientOcclusion(AppState.ambientOcclusion);
        }

        AppState.clipping.enabled = this.enabledValue;
    }
}

