import { RequestHandler, Txt2ImgRequest } from "../type/request";
import { txt2imgAPIformatJSON, txt2imgAPIformatExtraData } from "../comfyJson/txt2img";
import axios from "axios";
import { selectNodeFromApiJSONbyID } from "../utils/editComfyJson";
import WebSocket from "ws";
const baseUrl = "http://47.108.92.176:20000";
const baseWsUrl = "ws://47.108.92.176:20000";
// const baseUrl = "http://localhost:8188";
// const baseWsUrl = "ws://localhost:8188";
axios.defaults.baseURL = baseUrl;
const Txt2ImgHandler: RequestHandler<Txt2ImgRequest, any> = async (ctx, next) => {
    console.log(ctx.method);
    ctx.set('Access-Control-Allow-Origin', '*')
    ctx.set('Access-Control-Allow-Headers', 'Content-Type,Content-Length,Authorization,Accept,X-Requested-With')
    ctx.set('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
    if (ctx.method == 'OPTIONS') {
        ctx.body = 200;
        return;
    }
    const requestBody = ctx.request.body;
    const { prompt, loraDetail, loraModel } = requestBody;
    const inputNode = selectNodeFromApiJSONbyID(txt2imgAPIformatJSON, "33");
    let temp = "";
    inputNode.inputs.string = prompt;
    ctx.body = {
        data: await new Promise((resolve, reject) => {
            const taskID = Math.random().toFixed(10);
            const ws = new WebSocket(`${baseWsUrl}/ws?clientId=${taskID}`);
            ws.onopen = () => {
                try {
                    axios.post("/prompt", {
                        client_id: taskID,
                        prompt: txt2imgAPIformatJSON,
                        // extra_data: txt2imgAPIformatExtraData
                    });
                } catch (error) {
                    console.log(error);
                }

                ws.onmessage = (event) => {
                    if (typeof event.data === "string") {
                        const { type, data } = JSON.parse(event.data);
                        // if (type === "executed") {
                        //     if (data.node === '94') {
                        //         resolve(data.output.images[0].filename)
                        //     }
                        // }
                        if (type === "executed") {
                            if (data.node === '21') {
                                temp = data.output.text[0];
                            }
                            if (data.node === '94') {
                                resolve({ prompt: temp, url: baseUrl + '/view?filename=' + data.output.images[0].filename })
                            }
                        }
                    } else {

                    }
                }
            }
        })
    }
}
export default Txt2ImgHandler;