///|
fn csv_escape(text : String) -> String {
  if text.contains(",") || text.contains("\"") || text.contains("\n") {
    "\"" + text.replace(old="\"", new="\"\"") + "\""
  } else {
    text
  }
}

///|
pub fn products_to_csv(products : Array[Product]) -> String {
  let output = StringBuilder()
  output <+ "id,type,kind,global_id,name,description,tag,container\n"
  for product in products {
    let name = product.name.unwrap_or("")
    let description = product.description.unwrap_or("")
    let tag = product.tag.unwrap_or("")
    let container = product.container
      .map(value => value.to_string())
      .unwrap_or("")
    let row = product.id.to_string() +
      "," +
      csv_escape(product.ifc_type) +
      "," +
      csv_escape(product_kind_json(product.kind)) +
      "," +
      csv_escape(product.global_id.unwrap_or("")) +
      "," +
      csv_escape(name) +
      "," +
      csv_escape(description) +
      "," +
      csv_escape(tag) +
      "," +
      container +
      "\n"
    output <+ "\{row}"
  }
  output.to_string()
}

///|
pub fn property_sets_to_csv(property_sets : Array[PropertySet]) -> String {
  let output = StringBuilder()
  output <+ "set_id,set_name,property,description,value\n"
  for property_set in property_sets {
    for property in property_set.properties {
      let row = property_set.id.to_string() +
        "," +
        csv_escape(property_set.name.unwrap_or("")) +
        "," +
        csv_escape(property.name) +
        "," +
        csv_escape(property.description.unwrap_or("")) +
        "," +
        csv_escape(property.value.to_step_lossless()) +
        "\n"
      output <+ "\{row}"
    }
  }
  output.to_string()
}

///|
pub fn model_index_json(model : Model) -> String {
  let index = model.index()
  let histogram = type_histogram(index)
    .to_array()
    .map(item => {
      let (name, count) = item
      "{\"type\":" + json_string(name) + ",\"count\":" + count.to_string() + "}"
    })
  "{\"schema\":" +
  json_string(model.schema()) +
  ",\"entity_count\":" +
  model.entity_count().to_string() +
  ",\"types\":[" +
  join_json(histogram) +
  "]}"
}