import { RequestHandler, Txt2ImgRequest } from "../type/request";
import { upScaleAPIFormatJSON } from "../comfyJson/upscale";
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 UpscaleHandler: RequestHandler<any ,any> = async (ctx) => {
    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, url } = requestBody;
    const inputNode = selectNodeFromApiJSONbyID(upScaleAPIFormatJSON, "12");
    inputNode.inputs.image = url;
    ctx.body = {
        url: baseUrl + '/view?filename=' + 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: upScaleAPIFormatJSON,
                        // 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") {
                            console.log(data.output);
                            if (data.node === '47') {
                                resolve(data.output.images[0].filename)
                            }
                        }
                    } else {

                    }
                }
            }
        })
    }
}
export default UpscaleHandler;