#include "stdafx.h"

#include "xtr/io/SchemaExporter.h"

#include "xtr/cclDescriptor.h"
#include "xtr/io/RSForm2DOCX.h"

#include "ccl/tools/JSON.h"

namespace xtr::io {

namespace {

void OutputSchemaToCSV(std::ofstream& out, const ccl::semantic::RSForm& target) {
  // TODO: extract CSV writer and escape quotes in fields
  for (const auto uid : target.List()) {
    const auto& rsCst = target.GetRS(uid);
    const auto& textCst = target.GetText(uid);
    out << uid << ';';
    out << rsCst.alias << ';';
    out << '"' << mfc::ToSTL(info::Label(target.GetParse(uid).TypePtr())) << '"' << ';';
    out << '"' << rsCst.definition << '"' << ';';
    out << '"' << textCst.term.Nominal() << '"' << ';';
    out << '"' << textCst.definition.Str() << '"' << ';';
    out << '"' << rsCst.convention << '"' << ';';
    out << '\n';
  }
}

} // namespace

BOOL SchemaExporter::Export(const SchemaOptions& params, const CString fileName, const FileType type) {
  switch (type) {
  default: return FALSE;
  case FileType::docx: return io::RSForm2DOCX(target).Export(params, fileName);
  case FileType::csv: {
    std::ofstream file(fileName);
    if (!file.is_open()) {
      return FALSE;
    } else {
      OutputSchemaToCSV(file, target);
      file.close();
      return TRUE;
    }
  }
  case FileType::json: {
    std::ofstream file(fileName);
    if (!file.is_open()) {
      return FALSE;
    } else {
      file << std::setw(4) << nlohmann::ordered_json(target);
      file.close();
      return TRUE;
    }
  }
  }
}

} // namespace xtr::io