///|
pub fn plain_text(message : MailMessage) -> String {
  plain_from_part(message.root)
}

///|
fn plain_from_part(part : MailPart) -> String {
  if is_plain(part) {
    part.decoded_body
  } else {
    for child in part.children {
      let found = plain_from_part(child)
      if found != "" {
        return found
      }
    }
    ""
  }
}

///|
pub fn html_text(message : MailMessage) -> String {
  html_from_part(message.root)
}

///|
fn html_from_part(part : MailPart) -> String {
  if is_html(part) {
    part.decoded_body
  } else {
    for child in part.children {
      let found = html_from_part(child)
      if found != "" {
        return found
      }
    }
    ""
  }
}

///|
pub fn attachment_count(message : MailMessage) -> Int {
  count_attachments(message.root)
}

///|
fn count_attachments(part : MailPart) -> Int {
  let mut count = if is_attachment(part) { 1 } else { 0 }
  for child in part.children {
    count = count + count_attachments(child)
  }
  count
}

///|
pub fn part_count(message : MailMessage) -> Int {
  count_parts(message.root)
}

///|
fn count_parts(part : MailPart) -> Int {
  let mut count = 1
  for child in part.children {
    count = count + count_parts(child)
  }
  count
}

///|
pub fn summary(message : MailMessage) -> String {
  "From: " +
  join_addresses(message.from) +
  "\n" +
  "To: " +
  join_addresses(message.to) +
  "\n" +
  "Subject: " +
  message.subject +
  "\n" +
  "Date: " +
  message.date +
  "\n" +
  "Parts: " +
  part_count(message).to_string() +
  "\n" +
  "Attachments: " +
  attachment_count(message).to_string()
}

///|
fn join_addresses(items : Array[Address]) -> String {
  let mut out = ""
  let mut i = 0
  for item in items {
    if i > 0 {
      out = out + ", "
    }
    out = out + format_address(item)
    i = i + 1
  }
  out
}