import BaseView from "../../../core/BaseView.js";
import PermissionMatrixView from "./PermissionMatrixView.js";

export default class RoleEditorView extends BaseView {

    async onInit() {

        const id = this.props.roleId;

        this.role = id
            ? await this.api.get(`/roles/${id}`, { permission: "acl.role.view" })
            : { id: null, name: "", permissions: [] };
    }

    template() {
        return `
            <div class="ac-role-editor">
                <h2>${this.role.id ? "Edit Role" : "New Role"}</h2>

                <label>Name</label>
                <input data-ref="name" value="${this.role.name}" class="input"/>

                <button class="btn" data-ref="permBtn">Edit Permissions</button>

                <div class="actions">
                    <button class="btn-primary" data-ref="saveBtn">Save</button>
                </div>

                <div data-ref="matrixContainer"></div>
            </div>
        `;
    }

    onMounted() {

        this.ref("permBtn").addEventListener("click", () => {

            const matrix = new PermissionMatrixView({
                eventBus: this.eventBus,
                store: this.store,
                tab: this.tab,
                props: {
                    selected: this.role.permissions
                }
            });

            matrix.render(this.ref("matrixContainer"));

            matrix.onPermissionsChanged = (perms) => {
                this.role.permissions = perms;
            };

        });

        this.ref("saveBtn").addEventListener("click", () => this.save());
    }

    async save() {

        const name = this.ref("name").value.trim();

        const payload = {
            name,
            permissions: this.role.permissions
        };

        if (this.role.id) {
            await this.api.put(`/roles/${this.role.id}`, payload, {
                permission: "acl.role.edit"
            });
        } else {
            await this.api.post(`/roles`, payload, {
                permission: "acl.role.create"
            });
        }

        this.eventBus.emit("acl:role:updated");
    }

}
