import { Utils } from "../../Utils"

export default class PlantNet {
    public static baseUrl =
        "https://my-api.plantnet.org/v2/identify/all?api-key=2b10AAsjzwzJvucA5Ncm5qxe"

    public static async query(imageUrls: string[]): Promise<PlantNetResult | "no_plant_detected"> {
        if (imageUrls.length > 5) {
            throw "At most 5 images can be given to PlantNet.query"
        }
        if (imageUrls.length == 0) {
            throw "At least one image should be given to PlantNet.query"
        }
        let url = PlantNet.baseUrl
        for (const image of imageUrls) {
            url += "&images=" + encodeURIComponent(image)
        }

        const result = await Utils.downloadJsonCachedAdvanced(
            url,
            365 * 24 * 60 * 60 * 1000,
            undefined,
            true,
            1
        )
        if (result["content"]) {
            return result["content"]
        }
        const errResult = <
            {
                statusCode: 404
                error: "Not Found"
                message: "Species not found" | string
            }
        >JSON.parse(result["errContent"])
        if (errResult.message === "Species not found") {
            return "no_plant_detected"
        }
        const err = result["error"]
        console.log("Get error result:", err, ">>>>", result["errContent"])
        throw err
    }
}

export interface PlantNetSpeciesMatch {
    score: number
    gbif: { id: string /*Actually a number*/ }
    species: {
        scientificNameWithoutAuthor: string
        scientificNameAuthorship: string
        genus: {
            scientificNameWithoutAuthor: string
            scientificNameAuthorship: string
            scientificName: string
        }
        family: {
            scientificNameWithoutAuthor: string
            scientificNameAuthorship: string
            scientificName: string
        }
        commonNames: string[]
        scientificName: string
    }
}

export interface PlantNetResult {
    query: {
        project: string
        images: string[]
        organs: string[]
        includeRelatedImages: boolean
    }
    language: string
    preferedReferential: string
    bestMatch: string
    results: PlantNetSpeciesMatch[]
    version: string
    remainingIdentificationRequests: number
}
