import { Controller } from "@hotwired/stimulus"
import API_CONFIG from "../config.js";

/**
 * @todo Handle errors
 */
export default class extends Controller {
    static targets = [
        'building',
        'showBuilding',
        'buildingName',
        'buildingForm'
    ];

    API_BASE = API_CONFIG.dev;

    async submit(event) {
        event.preventDefault();

        if (event.currentTarget === this.buildingFormTarget) {
            const options = this.prepare(
                JSON.stringify({name: this.buildingTarget.value}),
                'POST'
            );

            const res = await this.send(
                `${this.API_BASE}/api/buildings`,
                options
            );

            if (res.id) {
                this.buildingTarget.setAttribute('data-id', res.id);
                this.showBuildingTarget.classList.remove('is-hidden');
                this.buildingNameTarget.textContent = res.name;
            }
        }
    }

    prepare(data, method) {
        return {
            headers: {
                "Content-Type": "application/json",
            },
            body: data,
            method,
        }
    }

    /**
     * @todo Return Exception on response error
     * @param {string} endpoint 
     * @param {object} options 
     * @returns 
     */
    async send(endpoint, options) {
        return await fetch(endpoint, options)
            .then(res => res.json())
            .catch(error => console.log(error));
    }
}