/*
 *   管理者コンソールバー用Script
 */
document.addEventListener('DOMContentLoaded', async () => {
    // 全頁共通 アクティビティ取得処理
    const notificationIcon = document.getElementById("notification");
    const notificationLink = document.getElementById("notification_link");
    if (notificationIcon == null || notificationLink == null) {
        return;
    }

    activityNotifications = await fetchActivityNotifications(true);
    if (activityNotifications !== "") {
        notificationIcon.classList.remove("fa-regular");
        notificationIcon.classList.add("fa-solid");
        notificationLink.style.color = "#cc0000";
    } else {
        activityNotifications = await fetchActivityNotifications(false);
        notificationLink.style.color = "#888888";
        if (activityNotifications == "") {
            activityNotifications = "新しい通知はありません";
        }
    }

    notificationIcon.addEventListener("click", async () => {
        showDialog(activityNotifications);
        await markNotificationsAsRead();
        notificationIcon.classList.remove("fa-solid");
        notificationIcon.classList.add("fa-regular");
        notificationLink.style.color = "#888888";
    });
});

//非同期通知取得
async function fetchActivityNotifications(no_read_only) {
    if (no_read_only) {
        params = "unreadonly=true";
    }
    else {
        params = "unreadonly=false";
    }
    try {
        const response = await fetch(`${BASE_URL}/api/v2/activity/get?${params}`, {
            method: 'GET',
        });

        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        const obj = await response.json();
        return obj.html;
    } catch (error) {
        console.error('Error fetching activity notifications:', error);
        throw error;
    }
}

//非同期通知既読化
async function markNotificationsAsRead() {
    try {
        const response = await fetch(`${BASE_URL}/api/v2/activity/readed`, {
            method: 'POST',
        });

        if (!response.ok) {
            throw new Error('Network response was not ok');
        }

        return await response.json()
    } catch (error) {
        console.error('Error marking notifications as read:', error);
        throw error;
    }
}

// 通知保持用
let activityNotifications = "";
