/*
 *
 *      メッセージ管理コンソール用 フロントエンド処理
 *  
 */

document.addEventListener("DOMContentLoaded", async () => {

    //イベント登録
    Q("#search_button").addEventListener("click", () => {
        searchExec();
    });
    Q("#search_clear_button").addEventListener("click", () => {
        Q(".search_input_form").value = "";
    });
    Q("#delete_button").addEventListener("click", async () => {
        await deleteExec();
    });

    QA(".list_item_created_at").forEach(tag => {
        tag.addEventListener("click", function (e) {
            showMessage(e);
        })
    });

    Q("#search_input_form").addEventListener("keydown", (e) => {
        if (e.keyCode == 13) {
            e.preventDefault();
            searchExec();
        }
    });

    Q("#sort_type").addEventListener("change", (e) => {
        e.preventDefault();
        searchExec();
    });

    QA(".search_word").forEach(tag => {
        tag.addEventListener("click", function () {
            tag = this.getAttribute("data-search");
            location.href = `${BASE_URL}/console/message?q=${encodeURIComponent(tag)}`;
        });
    });

    QA(".console_tag_cloud .tag").forEach(tag => {
        tag.addEventListener("click", () => {
            const tagText = tag.textContent.slice(1);
            window.location.href = `${BASE_URL}/console/message?q=%23${encodeURIComponent(tagText)}}`;
        });
    });

    const moreLink = Q(".console_tag_cloud .tag_cloud_more_link");
    if (moreLink) {
        moreLink.addEventListener("click", () => {
            Q(".tag-cloud-more").classList.toggle("visible");
        });
    }

});

//検索実行
function searchExec() {
    if (Q('#search_input_form').value != "検索...") {
        location.href = `${BASE_URL}/console/message?q=` + encodeURIComponent((Q('#search_input_form').value)) + '&sort_type=' + Q('#sort_type').value;
    }
}

//記事削除
async function deleteExec() {
    var targets = QA('.list_item_check:checked');
    if (targets.length == 0) {
        //チェックのついてる物がない
        await showDialog("対象を選択してください", "OK");
        return;
    }

    var ret = await showDialog("選択されたメッセージを削除していいですか？", "OK", "キャンセル");
    if (ret != "OK") {
        console.log("cancel");
        return;
    }

    var wait = window.waitDialog("処理中…");
    targets.forEach(async target => {
        await deleteLog(target.getAttribute('data-id'));
    });
    await new Promise((resolve) => setTimeout(resolve, 500));
    wait.close();
    //location.reload();

}

// 非同期削除処理本体
async function deleteLog(id) {
    try {
        let header = new Headers();
        header.append("X-CSRF-TOKEN", document.getElementById("csrf_token").value);

        const response = await fetch(`${BASE_URL}/api/messages/Q{id}`, {
            method: 'DELETE',
            header: header
        });

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

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

//選択メッセージの詳細表示処理
async function showMessage(event) {
    event.preventDefault();
    const clickedTd = event.target;
    const parentTr = clickedTd.parentElement.parentElement;
    const created_at = parentTr.querySelector('.list_item_created_at').textContent;
    const name = parentTr.querySelector('.list_item_name').textContent;
    const from_ip = parentTr.querySelector('.list_item_name').getAttribute('data-ip');
    const from_mail = parentTr.querySelector('.list_item_name').getAttribute('data-email');
    const from = "<a href=\"mailto:" + from_mail + "\">" + from_mail + "</a> / " + from_ip;
    const comment = parentTr.querySelector('.list_item_message').getAttribute('data-info');
    const id = parentTr.querySelector('.list_item_check').getAttribute('data-id');
    window.showDialog("<div class='comment_detail'><div class='detail_created_at'>" + created_at + "</div><div class='detail_name'>" + name + " <span class='detail_ip'>[" + from + "]</span></div><div class='detail_message'>" + comment + "</div></div>", 'OK');
    if (parentTr.classList.contains("unread")) {
        //既読設定
        readMessage(id);
        parentTr.classList.remove("unread");
    }
}

// 非同期既読処理本体
async function readMessage(id) {
    try {
        const formData = new FormData();
        formData.append('csrf_token', document.getElementById("csrf_token").value);
        const response = await fetch(`${BASE_URL}/api/v2/messages/Q{id}/read`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: formData
        });

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

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