import std/strutils

import ./reference_parser

type PassageQuery* = object
  reference*: PassageReference
  translation*: string

const SupportedTranslations* = [
  "akjv", "amp", "esv", "kjv", "mev", "niv", "nkjv"
]

proc supportedTranslationsList*(): string =
  SupportedTranslations.join(", ")

proc normalizeTranslation*(translation: string): string =
  result = translation.strip.toLowerAscii

  for supported in SupportedTranslations:
    if result == supported:
      return

  raise newException(ValueError,
    "unsupported translation '" & translation &
      "'; supported translations: " & supportedTranslationsList())

proc splitTrailingTranslationMarker(
    input: string): tuple[referenceText: string, translation: string] =

  let text = input.strip
  if not text.endsWith(")"):
    return (text, "")

  let openIdx = text.rfind("(")
  if openIdx < 0:
    return (text, "")

  let referenceText = text[0 ..< openIdx].strip
  let translation = text[openIdx + 1 ..< text.len - 1].strip
  if referenceText.len == 0 or translation.len == 0:
    return (text, "")

  (referenceText, translation)

proc parsePassageQuery*(input, defaultTranslation: string): PassageQuery =
  let parsed = splitTrailingTranslationMarker(input)
  result.reference = parseReference(parsed.referenceText)
  result.translation =
    if parsed.translation.len > 0:
      normalizeTranslation(parsed.translation)
    else:
      normalizeTranslation(defaultTranslation)

proc parsePassageQueries*(input, defaultTranslation: string): seq[PassageQuery] =
  for rawRef in input.split(';'):
    let refText = rawRef.strip
    if refText.len > 0:
      result.add(parsePassageQuery(refText, defaultTranslation))

  if result.len == 0:
    raise newException(ValueError, "empty Bible reference")

proc referenceText*(query: PassageQuery): string =
  $query.reference
