import { error, redirect } from '@sveltejs/kit'
import { base } from '$app/paths'

interface EnvUser {
    USER: DurableObjectNamespace
}

import type { Grain } from './grain-types'
export { Grain } from './grain-types'
import { SimulationCommunaute } from './simulation_communaute.js'
export { SimulationCommunaute } from './simulation_communaute.js'

export * from './common'

export async function userForm(
    env: EnvUser,
    id: DurableObjectId,
    body: Grain.CreateProjet
): Promise<Grain.CreateProjetResp>
export async function userForm(
    env: EnvUser,
    id: DurableObjectId,
    body: Grain.SaveProjet
): Promise<null>
export async function userForm(
    env: EnvUser,
    id: DurableObjectId,
    body: Grain.ListProjets
): Promise<Grain.ListProjetsResp>
export async function userForm(
    env: EnvUser,
    id: DurableObjectId,
    body: Grain.DelProjet
): Promise<null>
export async function userForm(
    env: EnvUser,
    id: DurableObjectId,
    body: Grain.GetProjet
): Promise<Grain.GetProjetResp>
export async function userForm(
    env: EnvUser,
    id: DurableObjectId,
    body: Grain.Cmd
): Promise<any> {
    let headers = new Headers()
    headers.set('Content-Type', 'application/json')
    let stub = env.USER.get(id)
    let x = await (
        await stub.fetch('https://y.coturnix.fr', {
            method: 'POST',
            body: JSON.stringify(body),
            headers,
        })
    ).text()
    console.log('userForm json', x)
    return JSON.parse(x)
}

export async function save(
    id_: DurableObjectId,
    params: { id?: string },
    request: Request,
    platform: Readonly<App.Platform>
) {
    const f = await request.formData()
    const data_ = f.get('data')
    let data
    if (data_) {
        console.log('data', data_)
        data = JSON.parse(data_ as string)
        if (!SimulationCommunaute(data)) {
            throw error(400, 'Bad request')
        }
    } else {
        throw error(400, 'Bad request')
    }
    const prms = JSON.parse(<string>f.get('prms') || '[]')
    const centrales = JSON.parse(<string>f.get('centrales') || '[]')
    const nom = <string>f.get('nom') || ''
    const porteur = <string>f.get('porteur') || ''
    const adresse = <string>f.get('adresse') || ''
    const tel = <string>f.get('tel') || ''
    const photo = <string | null>f.get('photo')

    console.log('params!', params)
    let pid
    if (params['id'] == 'nouveau') {
        pid = await userForm(platform.env, id_, {
            CreateProjet: {
                nom,
                porteur,
                tel,
                adresse,
                simulation: data,
                prms,
                centrales,
            },
        })
    } else if (params['id']) {
        pid = params['id']
        await userForm(platform.env, id_, {
            SaveProjet: {
                id: pid,
                nom,
                porteur,
                tel,
                adresse,
                simulation: data,
                prms,
                centrales,
            },
        })
    }

    console.log(pid, !!photo)

    /*if (photo) {
        console.log('photo')
        try {
            console.log('f')
            console.log(photo)
            await platform.env.projets.put(
                `photo.${id_.toString()}.${pid}`,
                photo
            )
            console.log('put')
        } catch (e) {
            console.log('Error', JSON.stringify(e))
        }
    }*/
    console.log('redirect', `${base}/projet/${pid}`)
    throw redirect(302, `${base}/projet/${pid}`)
}

export async function del(
    id_: DurableObjectId,
    params: { id?: string },
    platform: Readonly<App.Platform>
) {
    if (params.id) {
        await userForm(platform.env, id_, {
            DelProjet: {
                id: params['id'],
            },
        })
        throw redirect(302, `${base}`)
    }
}