import { Controller } from '@hotwired/stimulus';
//import UI from '../ui.js';
import BIM from '../bim.js';

/*
 * This is an example Stimulus controller!
 *
 * Any element with a data-controller="hello" attribute will cause
 * this controller to be executed. The name "hello" comes from the filename:
 * hello_controller.js -> "hello"
 *
 * Delete this file or adapt it for your use!
 */
export default class SceneController extends Controller {
    static targets = ['scene', 'load', 'building', 'modal'];

    connect() {
    }

    /**
     * @param {Element} container 
     */
    sceneTargetConnected(container) {
        this.setScene(container);
        //this.model = this.loadIfc();
        container.ondblclick = () => BIM.activateClipper();
        container.onkeydown = event => {
            console.log(event);
            if (event.code === 'Delete' || event.code === 'Backspace') {
                BIM.deleteClipper();
            }
        }
    }
    /**
     * @param {Element} container 
     */
    setScene(container) {
        BIM.createScene(container);
    }

    /**
     * @param {Element} container 
     * @param {String} btnId 
     */
    async loadIfc(event) {
        this.openModal();
        const nameInput = this.buildingTarget;
        let model = null;
        const files = event.target.files;
        model = await BIM.loadIfc(new Uint8Array(await files[0].arrayBuffer()), files[0].name);
        // Set a raycaster to select objects
        BIM.setupHighligther(model);
        localStorage.setItem('loaded-ifc', files[0].name);
        nameInput.value = files[0].name.replace('.ifc', '');
        this.closeModal();

        return model;
    }
    /**
     * 
     * @param {Event} event 
     */
    keyboard(event) {
        console.log(event);
    }
    /**
     * @todo Should be handled by ModalController...
     */
    openModal() {
        this.modalTarget.classList.add('is-active');
    }
    /**
     * @todo Should be handled by ModalController...
     */
    closeModal() {
        this.modalTarget.classList.remove('is-active');
    }
}