import { storage } from 'uxp'

declare let g_sd_url: string
export async function requestGet(url: string) {
    let data = null

    const full_url = url
    try {
        let request = await fetch(full_url)
        if (request.status === 404) {
            return null
        }

        const contentType = request.headers.get('content-type')
        if (contentType && contentType.includes('application/json')) {
            data = await request.json()
        } else if (
            contentType &&
            contentType.includes('application/octet-stream')
        ) {
            data = await request.arrayBuffer()
        } else if (
            contentType &&
            (contentType.includes('image/jpeg') ||
                contentType.includes('image/png'))
        ) {
            data = await request.arrayBuffer()
        } else {
            data = await request.text()
        }

        // console.log('data: ', data)
    } catch (e) {
        console.warn(`issues requesting from ${full_url}`, e)
    }
    return data
}

export async function requestPost(url: string, payload: any) {
    let json = null

    const full_url = url
    try {
        let request = await fetch(full_url, {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(payload),
        })

        if (request.status === 404) {
            return null
        }

        json = await request.json()

        // console.log('json: ', json)
    } catch (e) {
        console.warn(`issues requesting from ${full_url}`, e)
    }
    return json
}
export async function requestFormDataPost(url: string, payload: any) {
    try {
        var myHeaders = new Headers()
        myHeaders.append('Cookie', 'PHPSESSID=n70fa2vmvm6tfmktf4jmstmd1i')

        var formdata = new FormData()

        for (const [key, value] of Object.entries(payload)) {
            //@ts-ignore
            formdata.append(key, value)
        }
        // formdata.append(
        //     'source',
        //     'iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAApgAAAKYB3X3/OAAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAANCSURBVEiJtZZPbBtFFMZ/M7ubXdtdb1xSFyeilBapySVU8h8OoFaooFSqiihIVIpQBKci6KEg9Q6H9kovIHoCIVQJJCKE1ENFjnAgcaSGC6rEnxBwA04Tx43t2FnvDAfjkNibxgHxnWb2e/u992bee7tCa00YFsffekFY+nUzFtjW0LrvjRXrCDIAaPLlW0nHL0SsZtVoaF98mLrx3pdhOqLtYPHChahZcYYO7KvPFxvRl5XPp1sN3adWiD1ZAqD6XYK1b/dvE5IWryTt2udLFedwc1+9kLp+vbbpoDh+6TklxBeAi9TL0taeWpdmZzQDry0AcO+jQ12RyohqqoYoo8RDwJrU+qXkjWtfi8Xxt58BdQuwQs9qC/afLwCw8tnQbqYAPsgxE1S6F3EAIXux2oQFKm0ihMsOF71dHYx+f3NND68ghCu1YIoePPQN1pGRABkJ6Bus96CutRZMydTl+TvuiRW1m3n0eDl0vRPcEysqdXn+jsQPsrHMquGeXEaY4Yk4wxWcY5V/9scqOMOVUFthatyTy8QyqwZ+kDURKoMWxNKr2EeqVKcTNOajqKoBgOE28U4tdQl5p5bwCw7BWquaZSzAPlwjlithJtp3pTImSqQRrb2Z8PHGigD4RZuNX6JYj6wj7O4TFLbCO/Mn/m8R+h6rYSUb3ekokRY6f/YukArN979jcW+V/S8g0eT/N3VN3kTqWbQ428m9/8k0P/1aIhF36PccEl6EhOcAUCrXKZXXWS3XKd2vc/TRBG9O5ELC17MmWubD2nKhUKZa26Ba2+D3P+4/MNCFwg59oWVeYhkzgN/JDR8deKBoD7Y+ljEjGZ0sosXVTvbc6RHirr2reNy1OXd6pJsQ+gqjk8VWFYmHrwBzW/n+uMPFiRwHB2I7ih8ciHFxIkd/3Omk5tCDV1t+2nNu5sxxpDFNx+huNhVT3/zMDz8usXC3ddaHBj1GHj/As08fwTS7Kt1HBTmyN29vdwAw+/wbwLVOJ3uAD1wi/dUH7Qei66PfyuRj4Ik9is+hglfbkbfR3cnZm7chlUWLdwmprtCohX4HUtlOcQjLYCu+fzGJH2QRKvP3UNz8bWk1qMxjGTOMThZ3kvgLI5AzFfo379UAAAAASUVORK5CYII='
        // )
        // formdata.append('key', '6d207e02198a847aa98d0a2a901485a5')

        var requestOptions = {
            method: 'POST',
            headers: myHeaders,
            body: formdata,
            redirect: 'follow',
        }

        //@ts-ignore
        const response = await fetch(url, requestOptions)
        const result_json = response.json()
        return result_json
    } catch (e) {
        console.warn(e)
    }
}

export async function isScriptInstalled(script_name: string): Promise<boolean> {
    let is_installed = false
    try {
        const full_url = `${g_sd_url}/sdapi/v1/scripts`
        const scripts = await requestGet(full_url)
        is_installed =
            scripts?.txt2img?.includes(script_name) ||
            scripts?.img2img?.includes(script_name)
    } catch (e) {
        console.error(e)
    }
    console.log('is_installed: ', is_installed)
    return is_installed
}

export async function postArrayBuffer(url: string, data: Uint8Array) {
    const response = await fetch(url, {
        method: 'POST',
        body: data,
        headers: {
            'Content-Type': 'application/octet-stream', // or whatever type your data should be
        },
    })

    if (!response.ok) {
        throw new Error('Network response was not ok')
    }

    return response.json() // parses JSON response into native JavaScript objects
}

export async function postPng() {
    const new_file = await storage.localFileSystem.getFileForOpening()
    const arrayBuffer = await new_file.read({ format: storage.formats.binary })

    //@ts-ignore
    const extension_url = py_re.getExtensionUrl()
    const full_url = `${extension_url}/readPngMetadata`
    const json = await postArrayBuffer(full_url, new Uint8Array(arrayBuffer))
    //@ts-ignore
    // const json = await postArrayBuffer(full_url, 'ping')
    console.log('json:', json)
    return json
}
