package aza.instant.network

import io.ktor.client.HttpClient
import io.ktor.client.engine.cio.CIO
import io.ktor.client.plugins.HttpTimeoutConfig
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.plugins.timeout
import io.ktor.client.request.forms.MultiPartFormDataContent
import io.ktor.client.request.forms.append
import io.ktor.client.request.forms.formData
import io.ktor.client.request.headers
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.client.statement.HttpResponse
import io.ktor.http.ContentType
import io.ktor.serialization.kotlinx.json.json
import kotlinx.serialization.json.Json
import java.io.File

class BackendClient {

    private val client = HttpClient(CIO) {
        install(ContentNegotiation) {
            json(Json {
                prettyPrint = true
                isLenient = true
                ignoreUnknownKeys = true
            })
        }
    }

    companion object {
        private const val API_KEY = "meowmeow"
        private const val SERVER_URL = "http://172.16.0.212:3000" // For Android emulator
    }

    suspend fun uploadImage(ownerKey: String, originalPhoto: File, editedPhoto: File): HttpResponse {
        val origB = originalPhoto.readBytes()
        val editB = editedPhoto.readBytes()
        println(origB.size)
        println(editB.size)
        return client.post("$SERVER_URL/upload") {
            headers {
                append("x-instant-key", API_KEY)
            }
            setBody(
                MultiPartFormDataContent(formData {
                    append("owner_key", ownerKey)
                    append("\"photo\"", originalPhoto.name, ContentType.Image.JPEG, origB.size.toLong()) { write(origB) }
                    append("\"edited_photo\"", editedPhoto.name, ContentType.Image.JPEG, editB.size.toLong()) { write(editB) }
                })
            )
            timeout { HttpTimeoutConfig(1 * 60 * 1000L) }
        }
    }
}
