// SPDX-License-Identifier: MIT
#include <BRepTools.hxx>
#include <IGESCAFControl_Reader.hxx>
#include <Quantity_Color.hxx>
#include <TCollection_AsciiString.hxx>
#include <TDF_Tool.hxx>
#include <TDataStd_Name.hxx>
#include <TDocStd_Document.hxx>
#include <XCAFDoc_ColorTool.hxx>
#include <XCAFDoc_DocumentTool.hxx>
#include <XCAFDoc_ShapeTool.hxx>
#include <emscripten/bind.h>

#include <fstream>
#include <sstream>
#include <stdexcept>
#include <unordered_map>

using emscripten::val;

namespace {
struct Assembly {
  occ::handle<XCAFDoc_ShapeTool> shapes;
  occ::handle<XCAFDoc_ColorTool> colors;
  val parts = val::array();
  val prototypes = val::array();
  std::unordered_map<std::string, unsigned> known;
  unsigned partCount = 0;

  static std::string nameOf(const TDF_Label& label) {
    occ::handle<TDataStd_Name> name;
    if (!label.FindAttribute(TDataStd_Name::GetID(), name)) return {};
    const auto& wide = name->Get();
    std::string text(wide.LengthOfCString() + 1, '\0');
    auto ptr = text.data();
    wide.ToUTF8CString(ptr);
    text.resize(wide.LengthOfCString());
    return text;
  }

  val colorOf(const TDF_Label& label, val inherited) {
    Quantity_Color color;
    if (!colors->GetColor(label, XCAFDoc_ColorSurf, color) &&
        !colors->GetColor(label, XCAFDoc_ColorGen, color)) return inherited;
    double r, g, b;
    color.Values(r, g, b, Quantity_TOC_sRGB);
    return val::array(std::vector<double>{r, g, b});
  }

  val walk(const TDF_Label& label, const TopLoc_Location& parent, val color) {
    TDF_Label prototype;
    if (!shapes->GetReferredShape(label, prototype)) prototype = label;
    const auto placement = parent * shapes->GetLocation(label);
    color = colorOf(label, colorOf(prototype, color));
    auto name = nameOf(label);
    if (name.empty() || (label != prototype && name[0] == '>')) name = nameOf(prototype);
    if (name.empty()) name = "IGES part";
    val node = val::object();
    node.set("name", name);
    NCollection_Sequence<TDF_Label> children;
    shapes->GetComponents(prototype, children);
    if (!children.IsEmpty()) {
      val branches = val::array();
      for (int i = 1; i <= children.Length(); ++i) {
        branches.set(i - 1, walk(children.Value(i), placement, color));
      }
      node.set("children", branches);
      return node;
    }

    auto shape = shapes->GetShape(prototype);
    if (shape.IsNull()) return node;
    // The occurrence placement already contains the leaf label's location.
    if (label == prototype) shape.Location(TopLoc_Location());
    TCollection_AsciiString entry;
    TDF_Tool::Entry(prototype, entry);
    auto [item, inserted] = known.try_emplace(entry.ToCString(), known.size());
    if (inserted) {
      std::ostringstream brep;
      BRepTools::Write(shape, brep, false, false, TopTools_FormatVersion_CURRENT);
      prototypes.set(item->second, brep.str());
    }
    const auto& matrix = placement.Transformation();
    std::vector<double> columns;
    for (int column = 1; column <= 4; ++column) {
      for (int row = 1; row <= 3; ++row) columns.push_back(matrix.Value(row, column));
      columns.push_back(column == 4 ? 1 : 0);
    }
    val part = val::object();
    part.set("prototype", item->second);
    part.set("name", name);
    part.set("color", color);
    part.set("matrix", val::array(columns));
    node.set("parts", val::array(std::vector<unsigned>{partCount}));
    parts.set(partCount++, part);
    return node;
  }
};

val readIgesBrep(val bytes) {
  const char* path = "/source.igs";
  struct Remove { const char* path; ~Remove() { std::remove(path); } } cleanup{path};
  const auto length = bytes["length"].as<unsigned>();
  {
    std::vector<char> raw(length);
    val(emscripten::typed_memory_view(raw.size(), raw.data())).call<void>("set", bytes);
    std::ofstream file(path, std::ios::binary);
    file.write(raw.data(), raw.size());
    if (!file) throw std::runtime_error("Could not prepare the IGES input");
  }
  IGESCAFControl_Reader reader;
  reader.SetColorMode(true);
  reader.SetNameMode(true);
  occ::handle<TDocStd_Document> document = new TDocStd_Document(TCollection_ExtendedString("BinXCAF"));
  if (reader.ReadFile(path) != IFSelect_RetDone || !reader.Transfer(document)) {
    return val::null();
  }
  Assembly assembly{XCAFDoc_DocumentTool::ShapeTool(document->Main()), XCAFDoc_DocumentTool::ColorTool(document->Main())};
  NCollection_Sequence<TDF_Label> roots;
  assembly.shapes->GetFreeShapes(roots);
  val tree = val::array();
  for (int i = 1; i <= roots.Length(); ++i) tree.set(i - 1, assembly.walk(roots.Value(i), TopLoc_Location(), val::undefined()));
  val result = val::object();
  result.set("parts", assembly.parts);
  result.set("prototypes", assembly.prototypes);
  result.set("tree", tree);
  return result;
}
}

EMSCRIPTEN_BINDINGS(cad_iges_brep) {
  emscripten::function("readIgesBrep", &readIgesBrep);
}
