#!/usr/local/bin/ruby18 -w
# -*- ruby -*-

### or use this for profiling:
#!/usr/local/bin/ruby18 -w -rprofile

# require 'profile'

require 'getoptlong'

$PACKAGE = "phraze"
$VERSION = "0.4"

$verbose = false

$PHRAZE_DIR  = ENV["PHRAZE_DIR"] || "/usr/local/share/phraze"

$WORDLIST = $PHRAZE_DIR + "/wordlist.phr"

# for debugging
def blather(str)
  puts Time.new.to_s + ": " + str if $verbose
end

if RUBY_VERSION['1.6.']
  # inject became standard in version 1.8
  module Enumerable
    def inject(n)
      each do |i|
        n = yield(n, i)
      end
      n
    end
  end
end

class Sequence

  attr_accessor :words
  attr_reader :num

  def initialize(num)
    blather("num: #{num}")
    @num = num
    @words = []
  end

  def to_s
    "#{@num} => #{@words}"
  end

end

class Sequences

  def initialize
    @sequences = Hash.new
  end

  def get_sequences(num)
    blather("getting sequences: #{num}")
    seqs = Array.new
    1.upto(num.length) do |len|
      if len < num.length
        lhs = num[0, len]
        rhs = num[len, num.length - len]

        seqs << [ get(lhs), get_sequences(rhs) ]
      else
        seqs << [ get(num) ]
      end
    end
    blather("done getting sequences.")
    seqs
  end

  def get(num)
    @sequences[num] ||= Sequence.new(num)
  end

  def read_word_list(wordlist)
    blather("reading word list: #{wordlist}")

    seqnums = @sequences.keys.sort do |a, b|
      blather("sorting")
      cmp = a.length <=> b.length
      if cmp == 0
        cmp = a.to_i <=> b.to_i
      end
      cmp
    end

    # blather("got sequence numbers: #{seqnums})

    start = Time.new

    maxlen = seqnums[-1] ? seqnums[-1].length : 0
    
    File.open(wordlist) do |file|
      file.each_line do |line|
        num, words = line.split(':')
        if seq = @sequences[num]
          seq.words = words.chomp.split(',')
          if num == seqnums[-1]
            break
          end
        elsif num.length > maxlen
          break
        end
      end
    end

    done = Time.new
    blather("elapsed time to read word list: #{done - start}")
  end

  ENDS_WITH_DIGIT   = Regexp.new('\d$')
  STARTS_WITH_DIGIT = Regexp.new('^\d')

  def get_words(seq)
    start = Time.new

    words = []
    if seq.kind_of?(Array)
      if seq[0].kind_of?(Sequence)
        basewords = [ seq[0].num ]
        
        if seq[0].words.length > 0
          basewords.push(*seq[0].words)
        end

        if seq.length > 1
          seq[1 .. -1].each do |subseq|
            subwords = get_words(subseq)
            subwords.each do |subword|
              basewords.each do |baseword|
                if ENDS_WITH_DIGIT.match(baseword) && STARTS_WITH_DIGIT.match(subword)
                  words << baseword + subword
                else
                  words << baseword + " " + subword
                end
              end
            end
          end
        else
          words = basewords
        end
      else
        seq.each do |subseq|
          subwords = get_words(subseq)
          words.push(*subwords)
        end
      end
    else
      words << seq.num
      words.push(*seq.words)
    end
    words.uniq!
    blather("done getting words from: #{seq}")

    words
  end

end

def count_letters(str)
  ltrre = Regexp.new('[a-zA-Z]+')
  str.scan(Regexp.new(ltrre)).inject(0) { |s, x| s += x.length }
end

def collect_words(words, minlen, mintotal)
  blather("collecting words")

  start = Time.new

  if mintotal == nil
    if minlen == nil
      # nothing
    else
      re = Regexp.new('[a-zA-Z]{' + minlen.to_s + '}')
      words = words.select { |word| re.match(word) }
    end
  elsif minlen == nil
    ltrre = Regexp.new('[a-zA-Z]+')
    words = words.select { |word| word.scan(ltrre).inject(0) { |s, x| s += x.length } > mintotal }
  else
    re = Regexp.new('[a-zA-Z]{' + minlen.to_s + '}')
    ltrre = Regexp.new('[a-zA-Z]+')
    words = words.select { |word| re.match(word) && word.scan(ltrre).inject(0) { |s, x| s += x.length } > mintotal }
  end

  done = Time.new
  blather("elapsed time to collect #{words.length} words: #{done - start}")
  words
end    

def convert(min, len)
  if min != nil && min.kind_of?(Float)
    min = (len * min / 100).to_i
  end
  min
end

def get_percent_option(value)
  if Regexp.new('(\d+)%').match(value)
    min = value.to_f
  else
    min = value.to_i
  end
  min
end

def run(num, minlen = 0.33, mintotal = 0.50)
  num.gsub!(Regexp.new('[^\d+]'), '')

  seqmgr = Sequences.new
  seqs = seqmgr.get_sequences(num)

  seqmgr.read_word_list($WORDLIST)

  words    = seqmgr.get_words(seqs)
  minlen   = convert(minlen, num.length)
  mintotal = convert(mintotal, num.length)
  sorted   = collect_words(words, minlen, mintotal).reverse
  
  sorted
end

def show_help
  puts "USAGE"
  puts "    phraze [options] number..."
  puts ""
  puts "SUMMARY"
  puts "    Display phone number converted to words."
  puts ""
  puts "OPTIONS"
  puts "    -?, --help"
  puts "        Display this help message."
  puts ""
  puts "    -l NUM[%], --length=NUM[%]"
  puts "        Print only with a word of NUM matching characters, or "
  puts "        NUM minimum percentage of the length of the input number."
  puts ""
  puts "    -t NUM[%], --total=NUM[%]"
  puts "        Print only with a total of NUM matching characters, or "
  puts "        NUM minimum percentage of the length of the input number."
  puts ""
  puts "    -v, --version"
  puts "        Display version information and exit."
  puts ""
  puts "    -V, --verbose"
  puts "        Display normally suppressed output, for debugging purposes."
  puts ""
end

minlen = 0.33
mintotal = 0.50

if __FILE__ == $0
  opts = GetoptLong.new(
                        [ "--length",     "-l", GetoptLong::REQUIRED_ARGUMENT ],
                        [ "--total",      "-t", GetoptLong::REQUIRED_ARGUMENT ],
                        [ "--version",    "-v", GetoptLong::NO_ARGUMENT       ],
                        [ "--help",       "-?", GetoptLong::NO_ARGUMENT       ],
                        [ "--verbose",    "-V", GetoptLong::NO_ARGUMENT       ]
                        )

  opts.each do |o, a|
    case o
    when /length/
      minlen = get_percent_option(a)
    when /total/
      mintotal = get_percent_option(a)
    when /help/
      show_help
      exit
    when /version/
      print $PACKAGE, ", version ", $VERSION, "\n"
      print "Written by Jeff Pace (jpace@incava.org).\n"
      print "Released under the Lesser GNU Public License.\n"
      exit
    when /verbose/
      $verbose = true
    end
  end

  if ARGV.length == 0
    show_help
    exit
  end

  words = run(ARGV[0].dup, minlen, mintotal)

  words.each do |word|
    puts word
  end
end
