import { Grid } from "gridjs/dist/gridjs.umd.js";
import gridjs from "gridjs/dist/gridjs.umd.js";
import "gridjs/dist/gridjs.umd.js";
import GlobalConfig from "../../global-config";

class UsersTable {
    init() {
        this.initTableUsers();
    }

    initTableUsers() {
        new Grid({
            columns: [
                "ID",
                "Name",
                "Email",
                "Firstname",
                "Lastname",
                "Position",
                "Roles",
                {
                    name: "Action",
                    formatter: (cell) =>
                        gridjs.html(`
                            <div class="d-flex justify-content-center">
                                <a href="/master/users/${cell}/edit" class="btn btn-yellow btn-sm d-inline-flex align-items-center justify-content-center">
                                    <i class='bx bx-edit'></i>
                                </a>
                            </div>
                        `),
                },
            ],
            pagination: {
                limit: 15,
                server: {
                    url: (prev, page) =>
                        `${prev}${prev.includes("?") ? "&" : "?"}page=${
                            page + 1
                        }`,
                },
            },
            sort: true,
            search: {
                server: {
                    url: (prev, keyword) => `${prev}?search=${keyword}`,
                },
            },
            server: {
                url: `${GlobalConfig.apiHost}/api/users`,
                credentials: "include",
                headers: {
                    Authorization: `Bearer ${document
                        .querySelector('meta[name="api-token"]')
                        .getAttribute("content")}`,
                    "Content-Type": "application/json",
                },
                then: (data) => {
                    console.log(data.data);
                    return data.data.map((item) => [
                        item.id,
                        item.name,
                        item.email,
                        item.firstname,
                        item.lastname,
                        item.position,
                        item.roles,
                        item.id,
                    ]);
                },
                total: (data) => data.meta.total,
            },
        }).render(document.getElementById("table-users"));
    }
}

document.addEventListener("DOMContentLoaded", function (e) {
    new UsersTable().init();
});
