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.js";

class SyncronizeTask {
    init() {
        this.initTableImportDatasources();
        this.handleSubmitSync();
        this.handleSubmitSnycGoogleSheet();
    }
    initTableImportDatasources() {
        new Grid({
            columns: ["ID", "Message", "Response", "Status", "Created"],
            search: {
                server: {
                    url: (prev, keyword) => `${prev}?search=${keyword}`,
                },
            },
            pagination: {
                limit: 15,
                server: {
                    url: (prev, page) =>
                        `${prev}${prev.includes("?") ? "&" : "?"}page=${
                            page + 1
                        }`,
                },
            },
            sort: true,
            server: {
                url: `${GlobalConfig.apiHost}/api/import-datasource`,
                headers: {
                    Authorization: `Bearer ${document
                        .querySelector('meta[name="api-token"]')
                        .getAttribute("content")}`,
                    "Content-Type": "application/json",
                },
                then: (data) =>
                    data.data.map((item) => [
                        item.id,
                        item.message,
                        item.response_body,
                        item.status,
                        item.created_at,
                    ]),
                total: (data) => data.meta.total,
            },
        }).render(document.getElementById("table-import-datasources"));
    }
    handleSubmitSync() {
        const button = document.getElementById("btn-sync-submit");

        // Check if the button should be enabled or disabled based on the status
        fetch(
            `${GlobalConfig.apiHost}/api/import-datasource/check-datasource`,
            {
                method: "GET",
                headers: {
                    Authorization: `Bearer ${document
                        .querySelector('meta[name="api-token"]')
                        .getAttribute("content")}`,
                    "Content-Type": "application/json",
                },
            }
        )
            .then((response) => {
                if (!response.ok) {
                    throw new Error("Network response was not ok");
                }
                return response.json();
            })
            .then((data) => {
                console.log("data check button sync", data.can_execute);
                button.disabled = !data.can_execute;

                // If the button is enabled, add click event to trigger sync
                if (!button.disabled) {
                    button.addEventListener("click", function (e) {
                        button.disabled = true; // Disable button to prevent multiple clicks
                        button.textContent = "Syncing..."; // Change button text to show syncing

                        // Trigger the scraping API call
                        fetch(`${GlobalConfig.apiHost}/api/scraping`, {
                            method: "GET",
                            headers: {
                                Authorization: `Bearer ${document
                                    .querySelector('meta[name="api-token"]')
                                    .getAttribute("content")}`,
                                "Content-Type": "application/json",
                            },
                        })
                            .then((response) => {
                                if (!response.ok) {
                                    throw new Error(
                                        "Network response was not ok"
                                    );
                                }
                                return response.json();
                            })
                            .then((data) => {
                                console.log("data sync button", data);
                                alert("Synchronization executed successfully");
                                window.location.reload();
                            })
                            .catch((err) => {
                                console.error("Fetch error:", err);
                                alert(
                                    "An error occurred during synchronization"
                                );
                            })
                            .finally(() => {
                                button.disabled = false; // Re-enable the button after the request is complete
                                button.textContent = "Sync Data"; // Reset button text
                            });
                    });
                }
            })
            .catch((err) => {
                console.error("Fetch error:", err);
                alert("An error occurred while checking the datasource");
            });
    }
    handleSubmitSnycGoogleSheet() {
        const button = document.getElementById("btn-sync-submit-google-sheet");
        button.addEventListener("click", function (e) {
            button.disabled = true; // Disable button to prevent multiple clicks
            button.textContent = "Syncing..."; // Change button text to show syncing

            // Trigger the scraping API call
            fetch(`${GlobalConfig.apiHost}/api/sync-pbg-task-google-sheet`, {
                method: "GET",
                headers: {
                    Authorization: `Bearer ${document
                        .querySelector('meta[name="api-token"]')
                        .getAttribute("content")}`,
                    "Content-Type": "application/json",
                },
            })
                .then((response) => {
                    if (!response.ok) {
                        throw new Error("Network response was not ok");
                    }
                    return response.json();
                })
                .then((data) => {
                    console.log("data sync button", data);
                    alert("Synchronization executed successfully");
                    window.location.reload();
                })
                .catch((err) => {
                    console.error("Fetch error:", err);
                    alert("An error occurred during synchronization");
                })
                .finally(() => {
                    button.disabled = false; // Re-enable the button after the request is complete
                    button.textContent = "Sync Google Sheet"; // Reset button text
                });
        });
    }
}
document.addEventListener("DOMContentLoaded", function (e) {
    new SyncronizeTask().init();
});
