package lojban

import scala.util.Random

object SentenceGenerator {
  val vowels = "aeiou"
  val consonants = "bcdfgjklmnprstvxyz"

  def choose(array: Array[String]) =
    array(Random.nextInt(array.length))

  /** Returns either the result of calling the function, or the empty string */
  def maybe(function: => String) = if (Random.nextInt(2) == 0) function else ""

  /** Return true the given percentage of the time */
  def doPercent(percent: Int) = Random.nextInt(100) < percent
  
//  def maybe(s: String) = if (Random.nextInt(5) == 0) s else ""

  def join(s: String*) = (for (i <- s) yield i.trim).mkString(" ")

  /** Sentence is a Statement or a Predclaim */
  def makeSentence: String =
    if (doPercent(50)) makeStatement
    else makePredclaim

  /** Predclaim is a Predname BA Preds or a DA Preds */
  def makePredclaim: String =
    if (doPercent(50)) join(makePredname, makeBA, makePreds)
    else join(makeDA, makePreds)

  /** Preds is a Predstring or a Preds A Predstring */
  def makePreds: String =
    if (doPercent(90)) makePredstring
    else join(makePreds, makeA, makePredstring)

  /** Predname is a LA Predstring or a NAME */
  def makePredname: String =
    if (doPercent(50)) join(makeLA, makePredstring)
    else makeNAME

  /** Predstring is a PRED or a Predstring PRED */
  def makePredstring: String = {
    if (doPercent(80)) makePRED
    else join(makePRED, makePredstring)
  }

  /** Statement is a Predname Verbpred Predname or a Predname Verbpred */
  def makeStatement: String =
    join(makePredname, makeVerbpred, maybe(makePredname))

  /** Verbpred is a MOD Predstring */
  def makeVerbpred: String =
    join(makeMOD, makePredstring)

  /** A is "a" or "e" or "i" or "o" or "u" */
  def makeA: String = choose("a e i o u".split(" "))

  /** MOD is "ga" or "ge" or "gi" or "go" or "gu" */
  def makeMOD: String = "g" + choose("a e i o u".split(" "))

  /** BA is "ba" or "be" or "bi" or "bo" or "bu" */
  def makeBA: String = "b" + choose("a e i o u".split(" "))

  /** DA is "da" or "de" or "di" or "do" or "du" */
  def makeDA: String = "d" + choose("a e i o u".split(" "))

  /** LA is "la" or "le" or "li" or "lo" or "lu" */
  def makeLA: String = "l" + choose("a e i o u".split(" "))

  /** NAME is any name (must end in a consonant) */
  def makeNAME: String = {
    var name = ""
    val letters = consonants + vowels
    for (i <- 1 to Random.nextInt(5)) {
      name += letters(Random.nextInt(letters.length))
    }
    name + consonants(Random.nextInt(consonants.length))
  }

  /** PRED is any predicate -- must have the form CCVCV or CVCCV */
  def makePRED: String = {
    def C = choose((consonants map (c => c.toString)).toArray)
    def V = choose((vowels map (c => c.toString)).toArray)
    val pred = if (Random.nextInt(2) == 0) C + V + C + C + V else C + C + V + C + V
    if (pred(0) != pred(1) && pred(2) != pred(3)) pred else makePRED
  }
}