// MBTiles: a tileset's metadata, a tile by z/x/y with the row flipped, a little tile server, and
// each of the layouts in use. The plugin reads the SQLite file itself, so nothing is locked and no
// second SQLite is linked beside Quillo's.
//
//   node standins/mbtiles_sample.mjs      makes the sample files
//   quillo run mbtiles.qwe
//   then open http://localhost:8080/info, /tile/1/0/0, /tiles/2/1/3.png, /layouts and /refused

use "mbtiles.qwer"

let sample = "mbtiles_sample.mbtiles"

route GET /info = {
    info: mbtiles_info(sample)?,
    zooms: mbtiles_zooms(sample)?,
}

route GET /tile/:z(int)/:x(int)/:y(int) {
    let t = mbtiles_tile(sample, z, x, y)
    if is_err(t) { reply 400 t.error }
    t
}

// What a map library asks for. A real server would keep these files only for a moment.
route GET /tiles/:z(int)/:x(int)/:name {
    let y = int(split(name, ".")[0])
    let to = "data/mbtiles-" + str(z) + "-" + str(x) + "-" + str(y) + ".png"
    let t = mbtiles_tile_to_file(sample, z, x, y, to)?
    if !t.found { reply 404 "no such tile" }
    file(to)
}

// A tile runs onto overflow pages at zoom 3; each y is its own row, the flip showing.
route GET /check {
    let t = mbtiles_tile(sample, 3, 2, 5)?
    let low = mbtiles_tile(sample, 1, 1, 0)?
    {
        row: t.row,
        bytes: t.bytes,
        format: t.format,
        small: low.bytes,
        low_row: low.row,
        missing: mbtiles_tile(sample, 9, 0, 0)?.found,
        flip: [mbtiles_flip_y(3, 2)?, mbtiles_flip_y(3, 5)?],
        written: mbtiles_tile_to_file(sample, 1, 1, 0, "data/mbtiles-one.png")?,
    }
}

route GET /layouts {
    let d = "mbtiles_dedupe.mbtiles"
    let p = "mbtiles_plain.mbtiles"
    {
        dedupe: mbtiles_info(d)?.layout,
        shared: mbtiles_tile(d, 3, 0, 0)?.bytes == mbtiles_tile(d, 3, 7, 7)?.bytes,
        one: mbtiles_tile(d, 2, 1, 1)?.bytes,
        dedupe_zooms: mbtiles_zooms(d)?,
        plain: mbtiles_info(p)?,
        no_index: mbtiles_tile(p, 2, 1, 2)?,
        no_index_zooms: mbtiles_zooms(p)?,
        unpacked: mbtiles_tile_to_file(p, 2, 1, 2, "data/mbtiles-vector.pbf")?,
    }
}

route GET /refused = {
    off_the_map: mbtiles_tile(sample, 1, 5, 0).error,
    no_file: mbtiles_info("nothing.mbtiles").error,
    not_sqlite: mbtiles_info("mbtiles.qwe").error,
    zoom: mbtiles_flip_y(40, 0).error,
}
