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();
    });

    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?q=${encodeURI(tag)}`;
        });
    });

    /*
    QA(".console_tag_cloud .tag").forEach(tag => {
        tag.addEventListener("click", () => {
            const tagText = tag.textContent.slice(1);
            window.location.href = `${BASE_URL}/console?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?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("選択されたログを削除していいですか？<br>※画像も削除されます", "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 headers = new Headers();
        headers.append("X-CSRF-TOKEN", document.getElementById("csrf_token").value);

        console.log(`${BASE_URL}/api/v2/articles/${id}`);
        const response = await fetch(`${BASE_URL}/api/v2/articles/${id}`, {
            method: 'DELETE',
            headers: headers,
        });

        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return await response.json();
    } catch (error) {
        console.error('Error:', error);
        throw error;
    }
}