// ==UserScript==
// @name              T-excalidraw-远程同步
// @author            tianyunperfect
// @description       简介
// @version           1.0.0
// @update            2021-07-08 16:16:14
// @include           https://excalidraw.tianyunperfect.cn/?a=*
// @require           https://git.tianyunperfect.cn/tianyunperfect/web-base/raw/master/monkey/util.js?a=2022年06月26日21:06:37
// @require           https://cdn.bootcdn.net/ajax/libs/js-cookie/3.0.1/js.cookie.min.js
// @require           https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js


// ==/UserScript==
(async () => {
    if (window.top !== window.self) {
        return;
    }

    let key = "excalidraw";

    let id = getQueryString("a");
    axios.post(`https://web_history.tianyunperfect.cn/excalidraw/get`, {
        "id": id,
        "json_str": "[]"
    }).then(async res => {
        // 远程数据
        let data = res.data;
        if (data.message) {
            if (data.message != localStorage.getItem(key)) {
                localStorage.setItem(key, data.message);
                location.reload();
            }
        } else {
            await axios.post(`https://web_history.tianyunperfect.cn/excalidraw/insert`, {
                "id": id,
                "json_str": "[]"
            })
            localStorage.setItem(key, "[]");
            location.reload();
        }
        let json_str = localStorage.getItem(key);
        // 同步数据
        while (true) {
            await sleep(1000);
            let json_new = localStorage.getItem(key);
            if (json_str != json_new) {
                json_str = json_new;
                await axios.post(`https://web_history.tianyunperfect.cn/excalidraw/update`, {
                    "id": id,
                    "json_str": json_new
                });
            }
        }

    })
})();
