import { data } from "./main.ts";
import { Message } from "./protocol.ts";
import language_data from "./assets/locale.json.gz" with {type: "bytes"}

import schema from "./assets/locale.json" with {type: "json"}
export type Tr = { [key in keyof typeof schema]: string }

const TR: Tr = {} as Tr

export async function init_locale(lang?: string) {
    if (!lang) return await init_locale(select_language())
    const tk = JSON.parse(await decompress(language_data))
    for (const key in tk) {
        TR[key as keyof Tr] = tk[key][lang] ?? tk[key]["en"]
    }
}
async function decompress(data: Uint8Array): Promise<string> {
    const r = new ReadableStream({ start(c) { c.enqueue(data.buffer); c.close() } })
        .pipeThrough(new DecompressionStream("gzip"))
        .pipeThrough(new TransformStream({ start() { }, transform(ch, ct) { ct.enqueue(ch.buffer) } }))
        .pipeThrough(new TextDecoderStream())
    return (await Array.fromAsync(r)).join("")
}

export function tr(key: keyof Tr, ...args: string[]): string {
    let s = TR[key];
    if (!s) return key
    if (args.length) s = s.replace(/{(\d+)}/ig, (_m, index) => args[parseInt(index)])
    return s
}

function select_language(): string {
    const plang = (new URLSearchParams(globalThis.location.hash.substring(1))).get("lang")
    if (plang) return plang
    return navigator.language.split("-")[0] ?? "en"
}

export function message_str(m: Message): string {
    if ("text" in m) return m.text
    if ("translation" in m) return tr(m.translation.id as keyof Tr, ...m.translation.params.map(message_str))
    if ("tile" in m) return data.tile_names[m.tile]
    if ("item" in m) return data.item_names[m.item]
    return "[unknown message type]"
}
