// table: tables of data, column by column, like pandas' DataFrame: read
// from CSV, chosen, sorted, grouped, joined, summed, written back.
//
//   import "table"
//   t: table.table = table.load(file("sales.csv"))
//   print(t.show())
//   cheap: table.table = t.filter(fn(r: table.row): bool => r.float("price") < 10.0)
//   t.add("total", fn(r: table.row): json => r.float("price") * r.float("qty"))
//   print(t.group("city").sum("total").sort("total", true).head(5).show())
//   t.pick(["city", "total"]).save(file("out.csv"))
//
// Each column has one type, int, float or str, guessed from its values
// when a table is read: all ints make an int column, ints and floats a
// float one, anything else a str one. An empty cell is missing: the
// statistics pass it over, r.has(name) asks for it, and reading it raises
// table.MISSING. Errors: table.COLUMN (no such column, or a column of
// another type), table.MISSING, table.EMPTY (a statistic of no values).

pub lock COLUMN: int = 100
pub lock MISSING: int = 101
pub lock EMPTY: int = 102

// A table: named columns of one length.
pub obj table {
    cols: [str] = []        // the columns' names
    kinds: [str] = []       // their types: int, float or str
    ivals: [[int]] = []     // an int column's values (an empty list for the others)
    fvals: [[float]] = []
    svals: [[str]] = []
    gone: [[bool]] = []     // which of a column's cells are missing
    n: int = 0              // how many rows

    // len gives how many rows it has
    fn len(): int {
        return self.n
    }

    // names gives the columns' names
    fn names(): [str] {
        return self.cols
    }

    // kind gives a column's type: int, float or str
    fn kind(name: str): str {
        return self.kinds[at(self, name)]
    }

    // ints, floats and strs give a column's values (a missing one as 0,
    // 0.0 or ""); floats of an int column too, and strs of any
    fn ints(name: str): [int] {
        c: int = want(self, name, "int")
        return self.ivals[c]
    }

    fn floats(name: str): [float] {
        c: int = at(self, name)
        if self.kinds[c] == "int" {
            out: [float] = []
            self.ivals[c].walk(x) {
                f: float = convert(x)
                out[] = f
            }
            return out
        }
        want(self, name, "float")
        return self.fvals[c]
    }

    fn strs(name: str): [str] {
        c: int = at(self, name)
        if self.kinds[c] == "str" {
            return self.svals[c]
        }
        out: [str] = []
        (0..self.n - 1).walk(i) {
            out[] = cell(self, c, i)
        }
        return out
    }

    // head gives the first n rows, tail the last n
    fn head(n: int): table {
        return rows(self, span(0, min(n, self.n)))
    }

    fn tail(n: int): table {
        return rows(self, span(max(self.n - n, 0), self.n))
    }

    // pick gives a table of these columns, in this order
    fn pick(names: [str]): table {
        out: table = table {}
        names.walk(name) {
            column(out, self, at(self, name), name)
        }
        out.n = self.n
        return out
    }

    // drop gives a table without these columns
    fn drop(names: [str]): table {
        names.walk(name) {
            at(self, name)
        }
        keep: [str] = []
        self.cols.walk(c) {
            if !names.has(c) {
                keep[] = c
            }
        }
        return self.pick(keep)
    }

    // rename gives a column another name
    fn rename(old: str, name: str) {
        c: int = at(self, old)
        if old != name && self.cols.has(name) {
            throw error(COLUMN, "table: there is a column ${name} already")
        }
        self.cols[c] = name
    }

    // filter gives the rows keep says yes to
    fn filter(keep: fn(row): bool): table {
        r: row = row { t: self }
        picked: [int] = []
        (0..self.n - 1).walk(i) {
            r.i = i
            if keep(r) {
                picked[] = i
            }
        }
        return rows(self, picked)
    }

    // sort gives the rows in the order of a column (down: largest first);
    // equal ones keep their order, missing ones go last
    fn sort(name: str, down: bool = false): table {
        c: int = at(self, name)
        order: [int] = []
        last: [int] = []
        kind: str = self.kinds[c]
        // each value's rows, in order; then the values sorted
        if kind == "int" {
            by: {int: [int]} = {}
            vals: [int] = []
            (0..self.n - 1).walk(i) {
                if self.gone[c][i] {
                    last[] = i
                } else {
                    v: int = self.ivals[c][i]
                    if !has(by, v) {
                        by[v] = []
                        vals[] = v
                    }
                    by[v][] = i
                }
            }
            vals = vals.sort()
            if down {
                vals = vals.reverse()
            }
            vals.walk(v) {
                by[v].walk(i) {
                    order[] = i
                }
            }
        } else if kind == "float" {
            by: {str: [int]} = {}
            vals: [float] = []
            (0..self.n - 1).walk(i) {
                if self.gone[c][i] {
                    last[] = i
                } else {
                    f: float = self.fvals[c][i]
                    k: str = "${f}"
                    if !has(by, k) {
                        by[k] = []
                        vals[] = f
                    }
                    by[k][] = i
                }
            }
            vals = vals.sort()
            if down {
                vals = vals.reverse()
            }
            vals.walk(f) {
                by["${f}"].walk(i) {
                    order[] = i
                }
            }
        } else {
            by: {str: [int]} = {}
            vals: [str] = []
            (0..self.n - 1).walk(i) {
                if self.gone[c][i] {
                    last[] = i
                } else {
                    v: str = self.svals[c][i]
                    if !has(by, v) {
                        by[v] = []
                        vals[] = v
                    }
                    by[v][] = i
                }
            }
            vals = vals.sort()
            if down {
                vals = vals.reverse()
            }
            vals.walk(v) {
                by[v].walk(i) {
                    order[] = i
                }
            }
        }
        last.walk(i) {
            order[] = i
        }
        return rows(self, order)
    }

    // unique gives a column's values, each once, in the order they come
    fn unique(name: str): table {
        c: int = at(self, name)
        seen: {str} = {}
        picked: [int] = []
        (0..self.n - 1).walk(i) {
            k: str = key(self, c, i)
            if !has(seen, k) {
                seen[] = k
                picked[] = i
            }
        }
        return rows(self.pick([name]), picked)
    }

    // add adds a column, or replaces one, made by f for each row: ints,
    // floats or strs (null: missing)
    fn add(name: str, f: fn(row): json) {
        r: row = row { t: self }
        vals: [json] = []
        (0..self.n - 1).walk(i) {
            r.i = i
            vals[] = f(r)
        }
        put(self, name, vals)
    }

    // sum, mean, min, max and count of a number column (missing cells passed
    // over); count of any column
    fn sum(name: str): float {
        return numbers(self, name).sum()
    }

    fn mean(name: str): float {
        v: [float] = numbers(self, name)
        if len(v) == 0 {
            throw error(EMPTY, "table: ${name} has no values")
        }
        return v.mean()
    }

    fn min(name: str): float {
        v: [float] = numbers(self, name)
        if len(v) == 0 {
            throw error(EMPTY, "table: ${name} has no values")
        }
        return v.min()
    }

    fn max(name: str): float {
        v: [float] = numbers(self, name)
        if len(v) == 0 {
            throw error(EMPTY, "table: ${name} has no values")
        }
        return v.max()
    }

    fn count(name: str): int {
        c: int = at(self, name)
        k: int = 0
        self.gone[c].walk(g) {
            if !g {
                k = k + 1
            }
        }
        return k
    }

    // group groups the rows by a column's values, for sum, mean, min, max
    // and count of each group
    fn group(name: str): groups {
        c: int = at(self, name)
        g: groups = groups { t: self, col: c }
        where: {str: int} = {}
        (0..self.n - 1).walk(i) {
            k: str = key(self, c, i)
            if !has(where, k) {
                where[k] = len(g.firsts)
                g.firsts[] = i
                g.members[] = []
            }
            g.members[where[k]][] = i
        }
        return g
    }

    // join gives the rows of this table with the rows of other whose name
    // column has the same value; with all, also this table's rows without
    // one (other's columns missing there). Other's columns with a name this
    // table has already get "_2" after it.
    fn join(other: table, name: str, all: bool = false): table {
        c: int = at(self, name)
        oc: int = at(other, name)
        matches: {str: [int]} = {}
        (0..other.n - 1).walk(j) {
            if !other.gone[oc][j] {
                k: str = key(other, oc, j)
                if !has(matches, k) {
                    matches[k] = []
                }
                matches[k][] = j
            }
        }
        left: [int] = []
        right: [int] = []
        (0..self.n - 1).walk(i) {
            k: str = key(self, c, i)
            if !self.gone[c][i] && has(matches, k) {
                matches[k].walk(j) {
                    left[] = i
                    right[] = j
                }
            } else if all {
                left[] = i
                right[] = -1
            }
        }
        out: table = rows(self, left)
        (0..len(other.cols) - 1).walk(oi) {
            if oi == oc {
                skip
            }
            label: str = other.cols[oi]
            if out.cols.has(label) {
                label = "${label}_2"
            }
            vals: [json] = []
            right.walk(j) {
                if j < 0 || other.gone[oi][j] {
                    vals[] = null
                } else {
                    vals[] = value(other, oi, j)
                }
            }
            put(out, label, vals)
            if out.kinds[len(out.kinds) - 1] != other.kinds[oi] && other.kinds[oi] != "str" {
                retype(out, len(out.kinds) - 1, other.kinds[oi])
            }
        }
        return out
    }

    // describe gives count, mean, min and max of each number column
    fn describe(): table {
        names: [json] = []
        counts: [json] = []
        means: [json] = []
        mins: [json] = []
        maxs: [json] = []
        (0..len(self.cols) - 1).walk(c) {
            if self.kinds[c] != "str" {
                name: str = self.cols[c]
                names[] = name
                counts[] = self.count(name)
                if self.count(name) > 0 {
                    means[] = self.mean(name)
                    mins[] = self.min(name)
                    maxs[] = self.max(name)
                } else {
                    means[] = null
                    mins[] = null
                    maxs[] = null
                }
            }
        }
        out: table = table { n: len(names) }
        put(out, "column", names)
        put(out, "count", counts)
        put(out, "mean", means)
        put(out, "min", mins)
        put(out, "max", maxs)
        return out
    }

    // csv gives the table as CSV text, a header row first
    fn csv(sep: str = ","): str {
        all: [[str]] = [self.cols]
        (0..self.n - 1).walk(i) {
            line: [str] = []
            (0..len(self.cols) - 1).walk(c) {
                line[] = cell(self, c, i)
            }
            all[] = line
        }
        return all.csv(sep)
    }

    // save writes the table to a CSV file
    fn save(f: file, sep: str = ",") {
        f.write(self.csv(sep))
    }

    // show gives the table as aligned text: all rows if there are 20 or
    // fewer, else the first and last 5; then its size
    fn show(): str {
        picked: [int] = []
        if self.n <= 20 {
            (0..self.n - 1).walk(i) {
                picked[] = i
            }
        } else {
            (0..4).walk(i) {
                picked[] = i
            }
            picked[] = -1
            (self.n - 5..self.n - 1).walk(i) {
                picked[] = i
            }
        }
        lines: [[str]] = [self.cols]
        picked.walk(i) {
            line: [str] = []
            (0..len(self.cols) - 1).walk(c) {
                if i < 0 {
                    line[] = "..."
                } else if self.gone[c][i] {
                    line[] = ""
                } else {
                    line[] = cell(self, c, i)
                }
            }
            lines[] = line
        }
        widths: [int] = []
        (0..len(self.cols) - 1).walk(c) {
            w: int = 0
            lines.walk(l) {
                if len(l[c]) > w {
                    w = len(l[c])
                }
            }
            widths[] = w
        }
        out: [str] = []
        lines.walk(l) {
            if len(self.cols) == 0 {
                skip
            }
            parts: [str] = []
            (0..len(self.cols) - 1).walk(c) {
                if self.kinds[c] == "str" {
                    parts[] = l[c].rpad(widths[c])
                } else {
                    parts[] = l[c].lpad(widths[c])
                }
            }
            out[] = parts.join("  ").trim()
        }
        rs: str = "rows"
        if self.n == 1 {
            rs = "row"
        }
        cs: str = "columns"
        if len(self.cols) == 1 {
            cs = "column"
        }
        out[] = "[${self.n} ${rs} × ${len(self.cols)} ${cs}]"
        return out.join("\n")
    }
}

// A row, as filter and add see it.
pub obj row {
    t: table
    i: int = 0

    // has says whether a cell isn't missing
    fn has(name: str): bool {
        return !self.t.gone[at(self.t, name)][self.i]
    }

    fn int(name: str): int {
        c: int = want(self.t, name, "int")
        here(self, c, name)
        return self.t.ivals[c][self.i]
    }

    // float reads a float column, or an int one
    fn float(name: str): float {
        c: int = at(self.t, name)
        here(self, c, name)
        if self.t.kinds[c] == "int" {
            f: float = convert(self.t.ivals[c][self.i])
            return f
        }
        want(self.t, name, "float")
        return self.t.fvals[c][self.i]
    }

    // str reads a cell of any column, as text
    fn str(name: str): str {
        c: int = at(self.t, name)
        here(self, c, name)
        return cell(self.t, c, self.i)
    }
}

// The rows of a table in groups, by a column's values.
pub obj groups {
    t: table
    col: int = 0
    firsts: [int] = []        // each group's first row
    members: [[int]] = []     // each group's rows

    fn sum(name: str): table {
        return stat(self, name, "sum")
    }

    fn mean(name: str): table {
        return stat(self, name, "mean")
    }

    fn min(name: str): table {
        return stat(self, name, "min")
    }

    fn max(name: str): table {
        return stat(self, name, "max")
    }

    // count gives each group's number of rows, in a column count
    fn count(): table {
        out: table = rows(self.t.pick([self.t.cols[self.col]]), self.firsts)
        vals: [json] = []
        self.members.walk(m) {
            vals[] = len(m)
        }
        put(out, "count", vals)
        return out
    }
}

fn stat(g: groups, name: str, what: str): table {
    c: int = at(g.t, name)
    if g.t.kinds[c] == "str" {
        throw error(COLUMN, "table: ${name} is a str column, and ${what} takes numbers")
    }
    out: table = rows(g.t.pick([g.t.cols[g.col]]), g.firsts)
    vals: [json] = []
    g.members.walk(m) {
        nums: [float] = []
        m.walk(i) {
            if !g.t.gone[c][i] {
                nums[] = number(g.t, c, i)
            }
        }
        if len(nums) == 0 {
            vals[] = null
        } else if what == "sum" {
            vals[] = nums.sum()
        } else if what == "mean" {
            vals[] = nums.mean()
        } else if what == "min" {
            vals[] = nums.min()
        } else {
            vals[] = nums.max()
        }
    }
    put(out, name, vals)
    if what != "mean" && g.t.kinds[c] == "int" {
        retype(out, len(out.kinds) - 1, "int")
    }
    return out
}

// load reads a table from a CSV file: its first row names the columns
pub fn load(f: file, sep: str = ","): table {
    return parse(f.read(), sep)
}

// parse reads a table from CSV text
pub fn parse(text: str, sep: str = ","): table {
    all: [[str]] = text.csv(sep)
    t: table = table {}
    if len(all) == 0 {
        return t
    }
    header: [str] = all[0]
    t.n = len(all) - 1
    (0..len(header) - 1).walk(c) {
        name: str = header[c]
        if name == "" {
            name = "column${c + 1}"
        }
        if t.cols.has(name) {
            name = "${name}_${c + 1}"
        }
        vals: [str] = []
        (1..len(all) - 1).walk(i) {
            if c < len(all[i]) {
                vals[] = all[i][c]
            } else {
                vals[] = ""
            }
        }
        guess(t, name, vals)
    }
    return t
}

// guess adds a column of texts, of the type they are
fn guess(t: table, name: str, vals: [str]) {
    gone: [bool] = []
    kind: str = "int"
    ints: [int] = []
    vals.walk(s) {
        empty: bool = s == ""
        gone[] = empty
        if kind == "int" {
            n: int = 0
            if !empty {
                err: error = nil
                try err {
                    n = convert(s)
                }
                if err != nil {
                    kind = "float"
                }
            }
            ints[] = n
        }
    }
    floats: [float] = []
    if kind == "float" {
        vals.walk(s) {
            f: float = 0.0
            if kind == "float" && s != "" {
                err: error = nil
                try err {
                    f = convert(s)
                }
                if err != nil {
                    kind = "str"
                }
            }
            floats[] = f
        }
    }
    t.cols[] = name
    t.kinds[] = kind
    t.gone[] = gone
    if kind == "int" {
        t.ivals[] = ints
        t.fvals[] = []
        t.svals[] = []
    } else if kind == "float" {
        t.ivals[] = []
        t.fvals[] = floats
        t.svals[] = []
    } else {
        t.ivals[] = []
        t.fvals[] = []
        t.svals[] = vals
    }
}

// put adds (or replaces) a column of json values: ints, floats, strs or
// null (missing); its type is the widest of them
fn put(t: table, name: str, vals: [json]) {
    kind: str = "int"
    vals.walk(v) {
        if v is str {
            kind = "str"
        } else if v is float && kind == "int" {
            kind = "float"
        } else if !(v is int) && !(v is float) && !(v is null) {
            kind = "str"
        }
    }
    gone: [bool] = []
    ints: [int] = []
    floats: [float] = []
    strs: [str] = []
    vals.walk(v) {
        missing: bool = v is null
        gone[] = missing
        if kind == "int" {
            n: int = 0
            if !missing {
                n = convert(v)
            }
            ints[] = n
        } else if kind == "float" {
            f: float = 0.0
            if !missing {
                f = convert(v)
            }
            floats[] = f
        } else {
            s: str = ""
            if !missing {
                s = convert(v)
            }
            strs[] = s
        }
    }
    c: int = t.cols.index(name)
    if c < 0 {
        t.cols[] = name
        t.kinds[] = kind
        t.gone[] = gone
        t.ivals[] = ints
        t.fvals[] = floats
        t.svals[] = strs
        return
    }
    t.kinds[c] = kind
    t.gone[c] = gone
    t.ivals[c] = ints
    t.fvals[c] = floats
    t.svals[c] = strs
}

// retype makes column c of type kind again (after put widened it: a
// join's or a statistic's int column that has missing cells)
fn retype(t: table, c: int, kind: str) {
    if t.kinds[c] == kind || kind != "int" || t.kinds[c] != "float" {
        return
    }
    ints: [int] = []
    t.fvals[c].walk(f) {
        n: int = convert(f)
        ints[] = n
    }
    t.kinds[c] = "int"
    t.ivals[c] = ints
    t.fvals[c] = []
}

// at gives the place of a column, or raises table.COLUMN
fn at(t: table, name: str): int {
    c: int = t.cols.index(name)
    if c < 0 {
        throw error(COLUMN, "table: there is no column ${name} (there are ${t.cols.join(", ")})")
    }
    return c
}

// want gives the place of a column of a type, or raises table.COLUMN
fn want(t: table, name: str, kind: str): int {
    c: int = at(t, name)
    if t.kinds[c] != kind {
        throw error(COLUMN, "table: ${name} is ${an(t.kinds[c])} column, not ${kind}")
    }
    return c
}

fn an(kind: str): str {
    if kind == "int" {
        return "an int"
    }
    return "a ${kind}"
}

// here raises table.MISSING if a row's cell is missing
fn here(r: row, c: int, name: str) {
    if r.t.gone[c][r.i] {
        throw error(MISSING, "table: row ${r.i + 1} has no ${name}")
    }
}

// cell gives a cell's text ("" if missing)
fn cell(t: table, c: int, i: int): str {
    if t.gone[c][i] {
        return ""
    }
    if t.kinds[c] == "int" {
        return "${t.ivals[c][i]}"
    }
    if t.kinds[c] == "float" {
        return "${t.fvals[c][i]}"
    }
    return t.svals[c][i]
}

// key gives a cell's text for grouping and joining (missing: a key of its own)
fn key(t: table, c: int, i: int): str {
    if t.gone[c][i] {
        return "\0missing"
    }
    return cell(t, c, i)
}

// value gives a cell as json
fn value(t: table, c: int, i: int): json {
    if t.kinds[c] == "int" {
        return t.ivals[c][i]
    }
    if t.kinds[c] == "float" {
        return t.fvals[c][i]
    }
    return t.svals[c][i]
}

fn number(t: table, c: int, i: int): float {
    if t.kinds[c] == "int" {
        f: float = convert(t.ivals[c][i])
        return f
    }
    return t.fvals[c][i]
}

// numbers gives a number column's values that aren't missing, as floats
fn numbers(t: table, name: str): [float] {
    c: int = at(t, name)
    if t.kinds[c] == "str" {
        throw error(COLUMN, "table: ${name} is a str column, not a number column")
    }
    out: [float] = []
    (0..t.n - 1).walk(i) {
        if !t.gone[c][i] {
            out[] = number(t, c, i)
        }
    }
    return out
}

// rows gives a table of some rows, in this order
fn rows(t: table, picked: [int]): table {
    out: table = table { n: len(picked) }
    (0..len(t.cols) - 1).walk(c) {
        out.cols[] = t.cols[c]
        out.kinds[] = t.kinds[c]
        gone: [bool] = []
        ints: [int] = []
        floats: [float] = []
        strs: [str] = []
        kind: str = t.kinds[c]
        picked.walk(i) {
            gone[] = t.gone[c][i]
            if kind == "int" {
                ints[] = t.ivals[c][i]
            } else if kind == "float" {
                floats[] = t.fvals[c][i]
            } else {
                strs[] = t.svals[c][i]
            }
        }
        out.gone[] = gone
        out.ivals[] = ints
        out.fvals[] = floats
        out.svals[] = strs
    }
    return out
}

// column adds column c of t to out, by another name
fn column(out: table, t: table, c: int, name: str) {
    out.cols[] = name
    out.kinds[] = t.kinds[c]
    out.gone[] = t.gone[c]
    out.ivals[] = t.ivals[c]
    out.fvals[] = t.fvals[c]
    out.svals[] = t.svals[c]
}

// span gives the numbers from a up to b (not b)
fn span(a: int, b: int): [int] {
    out: [int] = []
    i: int = a
    while i < b {
        out[] = i
        i = i + 1
    }
    return out
}

fn min(a: int, b: int): int {
    if a < b {
        return a
    }
    return b
}

fn max(a: int, b: int): int {
    if a > b {
        return a
    }
    return b
}
