import {parse_gallery_response} from "../protocol/gallery_parser";
import {Gallery_Socket, gallery_socket_url} from "./gallery_socket";
import type {Gallery_Catalog} from "../protocol/gallery_types";

export function load_gallery_catalog(on_catalog: (catalog: Gallery_Catalog) => void, on_state: (state: string, message: string) => void): () => void {
    let disposed = false, completed = false, reconnect_timer: number | undefined;
    let socket: Gallery_Socket;
    const connect = () => {
        socket = new Gallery_Socket(gallery_socket_url(), {
            on_state: state => {
                if (disposed) return;
                if (state === "ready") socket.send("gallery_catalog");
                else if (state === "error") on_state("error", "目录连接错误 · 自动重连");
                else if (state === "closed" && !completed) reconnect_timer = window.setTimeout(connect, 1000);
            },
            on_binary: () => undefined,
            on_json: raw => {
                try {const response = parse_gallery_response(raw); if (response?.type === "catalog") {completed = true; on_catalog(response); on_state("ready", response.navigation.catalog_loaded_text); socket.close();} else if (response?.type === "error") on_state("error", response.message);} catch (error) {on_state("error", error instanceof Error ? error.message : "目录解析失败");}
            }
        });
        socket.connect();
    };
    connect();
    return () => {disposed = true; window.clearTimeout(reconnect_timer); socket?.close();};
}
