#!/usr/bin/ruby -w
# lotto_stats.rb - calculates lotto stats

require "dbi"

case ARGV[0]
  when /6.49/
    game = "6_49"
    max = 49
    
  when /6.45/
    game = "6_45"
    max = 45
   
  when /6.42/
    game = "6_42"
    max = 42
   
  else
  game = nil
  puts "\nPlease enter game type e.g.:\n ruby lotto_stats.rb 6-49\n"
 
end

if game

  begin
    # connect to the MySQL server
    dbh = DBI.connect("DBI:Mysql:lotto:localhost", "lotto", "")
   
    row = dbh.select_one("SELECT COUNT(*) FROM #{game}")
    row = row.to_s.to_i
   
    total = row * 6
         
    for num in 1..max
      row = dbh.select_one("SELECT COUNT(*)  FROM #{game} WHERE `d1` = #{num} OR `d2` = #{num} OR `d3` = #{num} OR `d4` = #{num} OR `d5` = #{num} OR `d6` = #{num}")
     
      chance = row.to_s.to_f / total * 100
     
      printf "%d %d %.2f\n", num, row.to_s, chance
     
    end
      
  rescue DBI::DatabaseError => e
    puts "An error occurred"
    puts "Error code: #{e.err}"
    puts "Error message: #{e.errstr}"
  ensure
    # disconnect from server
    dbh.disconnect if dbh
  end
end