// /AIWK_COMMON/modules/comm/wss_test.js
// AIWK EXT4 v039 · WSS 통신 테스트창: tab_id/token 상태등/재접속/로그 제어
(function () {
    "use strict";

    const AIWK = window.AIWK;
    function el(tag, cls, text) { const n = document.createElement(tag); if (cls) n.className = cls; if (text !== undefined) n.textContent = text; return n; }
    function pretty(v) { try { return JSON.stringify(v, null, 2); } catch (e) { return String(v); } }
    function nowIso(){ return new Date().toISOString(); }
    function makeBtn(label, fn, extra) { const b = document.createElement("button"); b.type = "button"; b.className = "aiwk-btn" + (extra ? " " + extra : ""); b.textContent = label; b.onclick = fn; return b; }
    function makeLogTools(out) {
        const line = el("div", "aiwk-comm-logline", "");
        const ck = document.createElement("input"); ck.type = "checkbox"; ck.checked = AIWK.comm ? AIWK.comm.getLogEnabled() : true;
        const label = document.createElement("label"); label.className = "select-text"; label.appendChild(ck); label.appendChild(document.createTextNode(" 로그"));
        const trash = makeBtn("🗑", function(){ out.textContent = ""; }, "aiwk-comm-trash"); trash.title = "로그 삭제";
        ck.onchange = function(){ if (AIWK.comm) AIWK.comm.setLogEnabled(ck.checked); };
        line.appendChild(label); line.appendChild(trash); line.appendChild(el("span", "select-text", "5000줄 초과 시 자동 정리"));
        return { line: line, checkbox: ck };
    }
    function logTo(out, title, obj) { if (AIWK.comm) AIWK.comm.appendToBox(out, title, obj, AIWK.comm.getLogEnabled(), 5000); }

    AIWK.modules.register("comm.wss_test", {
        name: "comm.wss_test",
        run: async function(ctx) { return { ok: 1, module: "comm.wss_test", win_id: ctx.win.id, status: AIWK.comm ? AIWK.comm.status() : {}, received: ctx.msg || {}, message: "WSS test window run completed" }; },
        mount: function(ctx) {
            const box = el("div", "space-y-2 text-sm select-text");
            const title = el("div", "text-base font-semibold", "WSS 통신 테스트창 v039");
            const desc = el("div", "text-xs", "WSS 연결/끊기/재접속/자동 재접속/송수신 로그를 여기서 봅니다.");
            const statusBar = el("div", "aiwk-comm-status-row", "");
            const topInfo = el("div", "aiwk-comm-top-info select-text", "tab_id/token 확인 전");
            const status = el("pre", "aiwk-auth-payload select-text", "");
            const toolbar = el("div", "aiwk-comm-toolbar", "");
            const autoLabel = el("label", "aiwk-checkbox", "");
            const auto = document.createElement("input"); auto.type = "checkbox"; autoLabel.appendChild(auto); autoLabel.appendChild(document.createTextNode(" WSS 자동 재접속"));
            const ms = document.createElement("input"); ms.className = "aiwk-input"; ms.value = "3000"; ms.placeholder = "재접속 ms";
            const target = document.createElement("input"); target.className = "aiwk-input"; target.value = "A*"; target.placeholder = "대상 예: A1 / A* / home.IG_CRM.room.A1#ext4";
            const action = document.createElement("input"); action.className = "aiwk-input"; action.value = "wss.test"; action.placeholder = "action";
            const payload = document.createElement("textarea"); payload.className = "aiwk-input"; payload.setAttribute("data-aiwk-textarea-key", "wss_payload"); payload.value = JSON.stringify({ text:"WSS 테스트", at:nowIso() }, null, 2);
            const out = el("pre", "aiwk-run-result select-text", "");
            const logTools = makeLogTools(out);
            function refresh(){
                const s = AIWK.comm ? AIWK.comm.status() : { error:"AIWK.comm missing" };
                const profile = (s && s.profile) || {};
                const auth = (s && s.wss && s.wss.auth) || {};
                const tabId = s.tab_id || "없음";
                const tokenText = profile.authToken ? "🔐" : "🔓";
                topInfo.textContent = "tab_id:" + tabId + " / " + tokenText + " / auth=" + (auth.auth_token_ok ? "OK" : "NO") + " / level=" + (auth.auth_level || "") + " / address=" + (s.address || "");
                topInfo.title = topInfo.textContent;
                status.textContent = pretty(s);
                if (AIWK.comm) AIWK.comm.renderStatusBar(statusBar);
                auto.checked = !!(s.wss && s.wss.auto_reconnect);
                ms.value = String((s.wss && s.wss.reconnect_ms) || ms.value || 3000);
                ctx.status.textContent = "WSS 상태: " + ((s.wss && s.wss.status) || "?") + " / tab:" + tabId + " / " + (s.indicator_text || "");
            }
            auto.onchange = function(){ const r = AIWK.comm.setAutoReconnect(auto.checked, ms.value); logTo(out, "자동 재접속 설정", r); refresh(); };
            toolbar.appendChild(makeBtn("접속", function(){ logTo(out, "WSS 접속", AIWK.comm.wssConnect({ force:false })); setTimeout(refresh, 300); }));
            toolbar.appendChild(makeBtn("끊기", function(){ logTo(out, "WSS 끊기", AIWK.comm.wssDisconnect("manual")); refresh(); }));
            toolbar.appendChild(makeBtn("재접속", function(){ logTo(out, "WSS 재접속", AIWK.comm.wssConnect({ force:true })); setTimeout(refresh, 300); }));
            toolbar.appendChild(makeBtn("설정 저장", function(){ logTo(out, "WSS 설정 저장", AIWK.comm.setAutoReconnect(auto.checked, ms.value)); refresh(); }));
            toolbar.appendChild(makeBtn("전송", function(){ let p={}; try{p=JSON.parse(payload.value||"{}");}catch(e){p={raw:payload.value};} logTo(out, "WSS 전송", AIWK.comm.wssSend(target.value, action.value, p, "ext4.wss-test")); refresh(); }));
            box.appendChild(title); box.appendChild(desc); box.appendChild(statusBar); box.appendChild(topInfo); box.appendChild(status); box.appendChild(autoLabel); box.appendChild(ms); box.appendChild(toolbar); box.appendChild(target); box.appendChild(action); box.appendChild(payload); box.appendChild(logTools.line); box.appendChild(out);
            ctx.body.appendChild(box); refresh();
            AIWK.events.on("comm:status", refresh);
            AIWK.events.on("comm:wss:message", function(packet){ logTo(out, "WSS 수신", packet); refresh(); });
        }
    });
}());
