#############################################################################
##
##  readxlsx.g
##
##  ReadXLSX( <filename>[, <nohead>][, <sheet>] )
##  XLSXSheetNames( <filename> )
##
##  ReadXLSX reads one worksheet of an Excel workbook in .xlsx format and
##  returns its rows as a list of records, following the conventions of
##  ReadCSV:
##
##  - The first non-empty row is taken as the header. Its entries become
##    the record component names, with blanks translated into underscores
##    (leading/trailing blanks are dropped). Empty header cells give names
##    "field<n>", where <n> is the column number (A=1, B=2, ...), and a
##    repeated header name gets "_<n>" appended so no column is lost.
##  - If <nohead> is given as true, there is no header row and the
##    components are called "field<n>".
##  - <sheet> selects the worksheet, either by position (an integer, in
##    the order of the tabs) or by name (a string). Default is the first.
##  - Each subsequent non-empty row gives one record. Empty cells are
##    left unbound, and entirely empty rows are skipped.
##
##  Cell values are converted as follows:
##
##  - text cells give strings (a number stored as text, such as a zip
##    code "00123", stays a string),
##  - integers give GAP integers,
##  - other numbers are, as in ReadCSV, returned as the decimal string
##    stored in the file (e.g. "0.25"), unless an option is given:
##      ReadXLSX( file : rationals )  gives exact rationals (1/4),
##      ReadXLSX( file : floats )     gives floats (0.25),
##  - TRUE/FALSE cells give true/false,
##  - cells formatted as dates or times give strings in ISO form
##    "2024-03-15", "2024-03-15 13:45:30" or "13:45:30",
##  - formula cells give the value last computed by the spreadsheet
##    program (the formula itself is ignored), error cells the error
##    text such as "#DIV/0!".
##
##  XLSXSheetNames returns the list of worksheet names of a workbook.
##
##  An .xlsx file is a zip archive of XML files. It is unpacked with the
##  external program `unzip' (or, if that is not available, `bsdtar' or
##  `tar', which can read zip archives on macOS, BSD and Windows 10+).
##  The XML is parsed by the small scanner below, so no packages are needed.
##
##  Example:
##    gap> Read("readxlsx.g");
##    gap> XLSXSheetNames("groups.xlsx");
##    [ "Groups", "Second Sheet" ]
##    gap> l:=ReadXLSX("groups.xlsx");;
##    gap> l[1];
##    rec( Group_Order := 2, Is_Abelian := true, Name := "C2", Ratio := "0.5" )
##    gap> ReadXLSX("groups.xlsx", "Second Sheet" : rationals);;
##
#############################################################################


#############################################################################
##
##  Decoding of XML text
##

# UTF-8 encoding of a Unicode code point
XLSX_UTF8 := function(n)
  if n < 128 then
    return [CHAR_INT(n)];
  elif n < 2048 then
    return List([192 + QuoInt(n, 64), 128 + n mod 64], CHAR_INT);
  elif n < 65536 then
    return List([224 + QuoInt(n, 4096), 128 + QuoInt(n, 64) mod 64,
                 128 + n mod 64], CHAR_INT);
  else
    return List([240 + QuoInt(n, 262144), 128 + QuoInt(n, 4096) mod 64,
                 128 + QuoInt(n, 64) mod 64, 128 + n mod 64], CHAR_INT);
  fi;
end;

# replace the XML entities &amp; &lt; &gt; &quot; &apos; &#nn; &#xhh;
XLSX_Unescape := function(s)
  local res, p, q, ent, n;
  if not '&' in s then
    return s;
  fi;
  res := "";
  p := 1;
  while true do
    q := Position(s, '&', p - 1);
    if q = fail then
      Append(res, s{[p..Length(s)]});
      return res;
    fi;
    Append(res, s{[p..q-1]});
    p := Position(s, ';', q);
    if p = fail then          # not well-formed, keep the rest as it is
      Append(res, s{[q..Length(s)]});
      return res;
    fi;
    ent := s{[q+1..p-1]};
    if ent = "amp" then
      Add(res, '&');
    elif ent = "lt" then
      Add(res, '<');
    elif ent = "gt" then
      Add(res, '>');
    elif ent = "quot" then
      Add(res, '"');
    elif ent = "apos" then
      Add(res, '\'');
    elif Length(ent) > 1 and ent[1] = '#' then
      if ent[2] in "xX" then
        n := IntHexString(ent{[3..Length(ent)]});
      else
        n := Int(ent{[2..Length(ent)]});
      fi;
      Append(res, XLSX_UTF8(n));
    else
      Append(res, s{[q..p]});
    fi;
    p := p + 1;
  od;
end;

# Excel escapes some characters in strings as _xHHHH_ (e.g. _x000D_ for a
# carriage return, and _x005F_ for a literal underscore before such a code)
XLSX_UnescapeX := function(s)
  local res, p, q;
  p := PositionSublist(s, "_x");
  if p = fail then
    return s;
  fi;
  res := "";
  q := 1;
  while p <> fail do
    if p + 6 <= Length(s) and s[p+6] = '_'
       and ForAll(s{[p+2..p+5]}, c -> c in "0123456789abcdefABCDEF") then
      Append(res, s{[q..p-1]});
      Append(res, XLSX_UTF8(IntHexString(s{[p+2..p+5]})));
      q := p + 7;
      p := PositionSublist(s, "_x", p + 6);
    else
      p := PositionSublist(s, "_x", p);
    fi;
  od;
  Append(res, s{[q..Length(s)]});
  return res;
end;

XLSX_DecodeString := s -> XLSX_UnescapeX(XLSX_Unescape(s));


#############################################################################
##
##  A minimal XML scanner. It only has to deal with the machine-written
##  XML inside .xlsx files, in which the elements we look for are never
##  nested inside elements of the same name. Namespace prefixes (as in
##  <x:row>, written by some libraries) are ignored.
##

# name of the tag whose '<' is at position <p>.
# Returns [ name as written, name without namespace prefix,
#           position after the name ]. The second entry is "" for end
# tags, comments and processing instructions.
XLSX_TagName := function(str, p)
  local len, q, raw, i;
  len := Length(str);
  q := p + 1;
  while q <= len and not str[q] in " \t\r\n/>" do
    q := q + 1;
  od;
  raw := str{[p+1..q-1]};
  if Length(raw) = 0 or raw[1] in "/?!" then
    return [raw, "", q];
  fi;
  i := Position(raw, ':');
  if i = fail then
    return [raw, raw, q];
  fi;
  return [raw, raw{[i+1..Length(raw)]}, q];
end;

# parse the attributes of a start tag, starting at position <q> (after the
# tag name). Returns [ record of attributes, position of the closing '>',
# true if the tag is of the form <.../> ]
XLSX_Attributes := function(str, q)
  local len, attr, eq, k, name, i, quote, close;
  len := Length(str);
  attr := rec();
  while true do
    while q <= len and str[q] in " \t\r\n" do
      q := q + 1;
    od;
    if q > len then
      Error("ReadXLSX: malformed XML (unterminated tag)");
    elif str[q] = '>' then
      return [attr, q, false];
    elif str[q] = '/' then
      return [attr, Position(str, '>', q), true];
    fi;
    eq := Position(str, '=', q);
    if eq = fail then
      Error("ReadXLSX: malformed XML (attribute without value)");
    fi;
    k := eq - 1;
    while str[k] in " \t\r\n" do
      k := k - 1;
    od;
    name := str{[q..k]};
    i := Position(name, ':');
    if i <> fail then
      name := name{[i+1..Length(name)]};
    fi;
    q := eq + 1;
    while str[q] in " \t\r\n" do
      q := q + 1;
    od;
    quote := str[q];
    close := Position(str, quote, q);
    attr.(name) := XLSX_Unescape(str{[q+1..close-1]});
    q := close + 1;
  od;
end;

# all elements <name ...>...</name> in <str>, as records with components
# attr (record of attributes), inner (the raw text between start and end
# tag), and start, stop (the positions of the first and last character)
XLSX_Elements := function(str, name)
  local res, len, p, t, a, closer, n, c, e;
  res := [];
  len := Length(str);
  p := Position(str, '<');
  while p <> fail do
    t := XLSX_TagName(str, p);
    if t[2] <> name then
      p := Position(str, '<', p);
    else
      a := XLSX_Attributes(str, t[3]);
      if a[3] then
        Add(res, rec(attr := a[1], inner := "", start := p, stop := a[2]));
        p := Position(str, '<', a[2]);
      else
        closer := Concatenation("</", t[1]);
        n := Length(closer);
        c := PositionSublist(str, closer, a[2]);
        while c <> fail and c + n <= len and not str[c+n] in " \t\r\n>" do
          c := PositionSublist(str, closer, c);
        od;
        if c = fail then
          Error("ReadXLSX: malformed XML (no ", closer, ">)");
        fi;
        e := Position(str, '>', c);
        Add(res, rec(attr := a[1], inner := str{[a[2]+1..c-1]},
                     start := p, stop := e));
        p := Position(str, '<', e);
      fi;
    fi;
  od;
  return res;
end;

# the text of a string item (<si> or <is>): the concatenation of all
# <t> elements, including those in rich text runs <r>, but ignoring the
# phonetic hints <rPh> used for East Asian text
XLSX_RichText := function(str)
  local res, p, e;
  if PositionSublist(str, "rPh") <> fail then
    res := "";
    p := 1;
    for e in XLSX_Elements(str, "rPh") do
      Append(res, str{[p..e.start-1]});
      p := e.stop + 1;
    od;
    Append(res, str{[p..Length(str)]});
    str := res;
  fi;
  res := "";
  for e in XLSX_Elements(str, "t") do
    Append(res, e.inner);
  od;
  return XLSX_DecodeString(res);
end;


#############################################################################
##
##  Access to the zip archive, via external programs
##

# run a program and return its standard output as a string, or fail
XLSX_RunProgram := function(prog, args)
  local str, out, res;
  str := "";
  out := OutputTextString(str, true);
  SetPrintFormattingStatus(out, false);
  res := Process(DirectoryCurrent(), prog, InputTextNone(), out, args);
  CloseStream(out);
  if res <> 0 then
    return fail;
  fi;
  return str;
end;

# returns a record with components `members' (list of file names in the
# archive) and `read' (a function that returns the contents of a member)
XLSX_OpenArchive := function(file)
  local f, magic, prog, list, name;

  f := InputTextFile(file);
  magic := [ReadByte(f), ReadByte(f)];
  CloseStream(f);
  if magic <> [80, 75] then     # "PK", the signature of a zip archive
    Error("ReadXLSX: ", file, " is not in .xlsx format.\n",
          "(Files in the old .xls format must first be saved as .xlsx or ",
          ".csv.)");
  fi;

  prog := Filename(DirectoriesSystemPrograms(), "unzip");
  if prog <> fail then
    list := XLSX_RunProgram(prog, ["-Z1", file]);
    if list <> fail then
      return rec(members := SplitString(list, "\r\n"),
                 read := m -> XLSX_RunProgram(prog, ["-p", file, m]));
    fi;
  fi;
  for name in ["bsdtar", "tar"] do
    prog := Filename(DirectoriesSystemPrograms(), name);
    if prog <> fail then
      list := XLSX_RunProgram(prog, ["-tf", file]);
      if list <> fail then
        return rec(members := SplitString(list, "\r\n"),
                   read := m -> XLSX_RunProgram(prog, ["-xOf", file, m]));
      fi;
    fi;
  od;
  Error("ReadXLSX: could not unpack ", file, ".\n",
        "This needs the program `unzip' (or `bsdtar') to be installed.");
end;


#############################################################################
##
##  The structure of the workbook
##

# path of the archive member <target>, given relative to directory <dir>
XLSX_ResolvePath := function(dir, target)
  local res, s;
  if Length(target) > 0 and target[1] = '/' then
    target := target{[2..Length(target)]};
  else
    target := Concatenation(dir, target);
  fi;
  res := [];
  for s in SplitString(target, "/") do
    if s = ".." then
      if Length(res) > 0 then
        Remove(res);
      fi;
    elif s <> "." and s <> "" then
      Add(res, s);
    fi;
  od;
  return JoinStringsWithSeparator(res, "/");
end;

# the relationships of the archive member <path>, as a list of records
# with components type (last part of the type URL) and target (full path)
XLSX_Relationships := function(zip, path)
  local p, dir, rels, res, e, t;
  p := Maximum(Concatenation([0], Positions(path, '/')));
  dir := path{[1..p]};
  rels := Concatenation(dir, "_rels/", path{[p+1..Length(path)]}, ".rels");
  res := [];
  if rels in zip.members then
    for e in XLSX_Elements(zip.read(rels), "Relationship") do
      if IsBound(e.attr.Target) and IsBound(e.attr.Id) then
        t := "";
        if IsBound(e.attr.Type) then
          t := SplitString(e.attr.Type, "/");
          t := t[Length(t)];
        fi;
        Add(res, rec(id := e.attr.Id, type := t,
                     target := XLSX_ResolvePath(dir, e.attr.Target)));
      fi;
    od;
  fi;
  return res;
end;

XLSX_FindFile := function(name)
  local file;
  file := UserHomeExpand(name);
  if not IsReadableFile(file)
     and IsReadableFile(Concatenation(file, ".xlsx")) then
    file := Concatenation(file, ".xlsx");
  fi;
  if not IsReadableFile(file) then
    Error("file ", name, " does not exist or is not readable");
  fi;
  return file;
end;

# returns a record describing the workbook: the archive, the list of
# sheets (records with name and path), the paths of the shared strings
# and the styles (or fail), and whether dates count from 1904
XLSX_OpenWorkbook := function(file)
  local zip, wbpath, r, wb, rels, sheets, e, i, wbpr, find;

  zip := XLSX_OpenArchive(file);
  wbpath := "xl/workbook.xml";
  if not wbpath in zip.members then
    # find the main part of the package from its relationships
    r := First(XLSX_Relationships(zip, ""), x -> x.type = "officeDocument");
    if r = fail or not r.target in zip.members then
      Error("ReadXLSX: ", file, " does not contain an Excel workbook");
    fi;
    wbpath := r.target;
  fi;
  wb := zip.read(wbpath);
  rels := XLSX_Relationships(zip, wbpath);

  find := function(type)
    local r;
    r := First(rels, x -> x.type = type);
    if r = fail or not r.target in zip.members then
      return fail;
    fi;
    return r.target;
  end;

  sheets := [];
  for e in XLSX_Elements(wb, "sheet") do
    i := PositionProperty(rels, x -> x.id = e.attr.id);
    if i <> fail then
      Add(sheets, rec(name := e.attr.name, path := rels[i].target));
    fi;
  od;

  wbpr := XLSX_Elements(wb, "workbookPr");

  return rec(
    zip := zip,
    sheets := sheets,
    sharedStrings := find("sharedStrings"),
    styles := find("styles"),
    date1904 := Length(wbpr) > 0 and IsBound(wbpr[1].attr.date1904)
                and wbpr[1].attr.date1904 in ["1", "true"]);
end;

XLSXSheetNames := function(name)
  return List(XLSX_OpenWorkbook(XLSX_FindFile(name)).sheets, s -> s.name);
end;


#############################################################################
##
##  Dates. Excel stores dates as numbers (days since 1900, or 1904) and
##  only the number format of the cell tells that it is a date.
##

# the built-in number formats that are dates or times
XLSX_BuiltinDateFormats := Concatenation([14..22], [27..36], [45..47],
                                         [50..58]);

# does a custom number format code describe a date or time?
XLSX_IsDateFormat := function(code)
  local s, i, c;
  code := LowercaseString(code);
  # elapsed times like [h]:mm are durations, not points in time
  if ForAny(["[h", "[m", "[s"], x -> PositionSublist(code, x) <> fail) then
    return false;
  fi;
  # drop quoted text, [colors/conditions/locales], and escaped characters
  s := "";
  i := 1;
  while i <= Length(code) do
    c := code[i];
    if c = '"' then
      i := Position(code, '"', i);
    elif c = '[' then
      i := Position(code, ']', i);
    elif c in "\\_*" then
      i := i + 1;
    else
      Add(s, c);
    fi;
    if i = fail then
      break;
    fi;
    i := i + 1;
  od;
  return ForAny("dmyhs", c -> c in s);
end;

# list whose i-th entry says whether cell style i-1 is a date format
XLSX_DateStyles := function(str)
  local custom, e, xfs, isdate;
  custom := rec();
  e := XLSX_Elements(str, "numFmts");
  if Length(e) > 0 then
    for e in XLSX_Elements(e[1].inner, "numFmt") do
      if IsBound(e.attr.numFmtId) and IsBound(e.attr.formatCode) then
        custom.(e.attr.numFmtId) := XLSX_IsDateFormat(e.attr.formatCode);
      fi;
    od;
  fi;
  isdate := function(e)
    local id;
    if not IsBound(e.attr.numFmtId) then
      return false;
    fi;
    id := e.attr.numFmtId;
    if IsBound(custom.(id)) then
      return custom.(id);
    fi;
    return Int(id) in XLSX_BuiltinDateFormats;
  end;
  xfs := XLSX_Elements(str, "cellXfs");
  if Length(xfs) = 0 then
    return [];
  fi;
  return List(XLSX_Elements(xfs[1].inner, "xf"), isdate);
end;

# ISO string for the (nonnegative, rational) Excel date value x
XLSX_DateString := function(x, date1904)
  local two, days, secs, dmy, str;
  two := function(n)
    if n < 10 then
      return Concatenation("0", String(n));
    fi;
    return String(n);
  end;
  days := Int(x);
  secs := Int((x - days) * 86400 + 1/2);
  if secs >= 86400 then
    days := days + 1;
    secs := secs - 86400;
  fi;
  str := "";
  if days > 0 then
    if date1904 then
      dmy := DMYDay(days - 24107);
    elif days < 60 then     # Excel wrongly thinks 1900 was a leap year
      dmy := DMYDay(days - 25568);
    else
      dmy := DMYDay(days - 25569);
    fi;
    str := Concatenation(String(dmy[3]), "-", two(dmy[2]), "-", two(dmy[1]));
  fi;
  if secs > 0 or days = 0 then
    if days > 0 then
      Add(str, ' ');
    fi;
    Append(str, Concatenation(two(QuoInt(secs, 3600)), ":",
                   two(QuoInt(secs, 60) mod 60), ":", two(secs mod 60)));
  fi;
  return str;
end;


#############################################################################
##
##  Cell values
##

# exact rational value of a decimal number string such as "-1.25E-3"
XLSX_DecimalRat := function(s)
  local e, p, sign, n;
  s := LowercaseString(s);
  e := 0;
  p := Position(s, 'e');
  if p <> fail then
    e := s{[p+1..Length(s)]};
    if Length(e) > 0 and e[1] = '+' then
      e := e{[2..Length(e)]};
    fi;
    e := Int(e);
    s := s{[1..p-1]};
  fi;
  sign := 1;
  if Length(s) > 0 and s[1] in "+-" then
    if s[1] = '-' then
      sign := -1;
    fi;
    s := s{[2..Length(s)]};
  fi;
  p := Position(s, '.');
  if p <> fail and e <> fail then
    e := e - (Length(s) - p);
    s := Concatenation(s{[1..p-1]}, s{[p+1..Length(s)]});
  fi;
  n := Int(s);
  if n = fail or e = fail then
    return fail;
  fi;
  return sign * n * 10^e;
end;

XLSX_Number := function(s, mode)
  local n;
  n := Int(s);
  if n <> fail then
    return n;
  elif mode = "rational" then
    n := XLSX_DecimalRat(s);
  elif mode = "float" then
    n := Float(s);
  fi;
  if n = fail then
    return s;
  fi;
  return n;
end;

# column number of a cell reference such as "AB12"
XLSX_Column := function(ref)
  local n, c, k;
  n := 0;
  for c in ref do
    k := INT_CHAR(c);
    if k < 65 or k > 90 then
      return n;
    fi;
    n := 26 * n + k - 64;
  od;
  return n;
end;

# value of the cell <c> (as returned by XLSX_Elements), or fail if empty
XLSX_CellValue := function(c, wb, mode)
  local t, v, s, x;
  if IsBound(c.attr.t) then
    t := c.attr.t;
  else
    t := "n";
  fi;
  if t = "inlineStr" then
    v := XLSX_Elements(c.inner, "is");
    if Length(v) = 0 then
      return fail;
    fi;
    v := XLSX_RichText(v[1].inner);
  else
    v := XLSX_Elements(c.inner, "v");
    if Length(v) = 0 then       # empty, or a formula never computed
      return fail;
    fi;
    v := v[1].inner;
    if Length(v) = 0 then
      return fail;
    fi;
    if t = "s" then             # shared string
      v := wb.sst[Int(v) + 1];
    elif t = "str" then         # string computed by a formula
      v := XLSX_DecodeString(v);
    elif t = "b" then
      return v in ["1", "true"];
    elif t = "e" or t = "d" then  # error value; date in ISO form
      v := XLSX_Unescape(v);
    else                        # number
      if IsBound(c.attr.s) then
        s := Int(c.attr.s) + 1;
        if IsBound(wb.datestyles[s]) and wb.datestyles[s] then
          x := XLSX_DecimalRat(v);
          if x <> fail and x >= 0 then
            return XLSX_DateString(x, wb.date1904);
          fi;
        fi;
      fi;
      return XLSX_Number(v, mode);
    fi;
  fi;
  if Length(v) = 0 then
    return fail;
  fi;
  return v;
end;


#############################################################################
##
#F  ReadXLSX( <filename>[, <nohead>][, <sheet>] )
##
ReadXLSX := function(arg)
  local file, nohead, sheet, mode, wb, i, x, xml, rows, row, vals, col,
        c, v, ncols, head, fields, name, res, r;

  file := XLSX_FindFile(arg[1]);
  nohead := false;
  sheet := 1;
  for x in arg{[2..Length(arg)]} do
    if IsBool(x) then
      nohead := x;
    elif IsPosInt(x) or IsString(x) then
      sheet := x;
    else
      Error("usage: ReadXLSX( <filename>[, <nohead>][, <sheet>] )");
    fi;
  od;
  if ValueOption("rationals") = true then
    mode := "rational";
  elif ValueOption("floats") = true then
    mode := "float";
  else
    mode := "string";
  fi;

  wb := XLSX_OpenWorkbook(file);
  if IsString(sheet) then
    i := PositionProperty(wb.sheets, s -> s.name = sheet);
    if i = fail then
      Error("ReadXLSX: ", file, " has no sheet named \"", sheet,
            "\". Its sheets are ", List(wb.sheets, s -> s.name));
    fi;
  else
    i := sheet;
    if i > Length(wb.sheets) then
      Error("ReadXLSX: ", file, " has only ", Length(wb.sheets), " sheet(s)");
    fi;
  fi;

  if wb.sharedStrings <> fail then
    wb.sst := List(XLSX_Elements(wb.zip.read(wb.sharedStrings), "si"),
                   e -> XLSX_RichText(e.inner));
  else
    wb.sst := [];
  fi;
  if wb.styles <> fail then
    wb.datestyles := XLSX_DateStyles(wb.zip.read(wb.styles));
  else
    wb.datestyles := [];
  fi;

  # collect the non-empty rows as lists indexed by column number
  xml := XLSX_Elements(wb.zip.read(wb.sheets[i].path), "sheetData");
  if Length(xml) = 0 then       # e.g. a chart sheet
    return [];
  fi;
  rows := [];
  for row in XLSX_Elements(xml[1].inner, "row") do
    vals := [];
    col := 0;
    for c in XLSX_Elements(row.inner, "c") do
      if IsBound(c.attr.r) then
        col := XLSX_Column(c.attr.r);
      else
        col := col + 1;
      fi;
      v := XLSX_CellValue(c, wb, mode);
      if v <> fail then
        vals[col] := v;
      fi;
    od;
    if Length(vals) > 0 then
      Add(rows, vals);
    fi;
  od;
  if Length(rows) = 0 then
    return [];
  fi;

  # component names
  ncols := Maximum(List(rows, Length));
  if nohead = true then
    fields := List([1..ncols], i -> Concatenation("field", String(i)));
  else
    head := rows[1];
    rows := rows{[2..Length(rows)]};
    fields := [];
    for i in [1..ncols] do
      name := "";
      if IsBound(head[i]) then
        name := head[i];
        if not IsString(name) then
          name := String(name);
        fi;
        name := ReplacedString(NormalizedWhitespace(name), " ", "_");
      fi;
      if Length(name) = 0 then
        name := Concatenation("field", String(i));
      elif name in fields then
        name := Concatenation(name, "_", String(i));
      fi;
      Add(fields, name);
    od;
  fi;

  res := [];
  for vals in rows do
    r := rec();
    for i in [1..Length(vals)] do
      if IsBound(vals[i]) then
        r.(fields[i]) := vals[i];
      fi;
    od;
    Add(res, r);
  od;
  return res;
end;
