require 'fastercsv'


class Map < ActiveRecord::Base
  def self.from_city_name(city_name)
    self.find_or_initialize_by_name(city_name).save!
  end

  def self.pair
    second = nil
    max_tries = self.count
    tries = 0

    while second.nil? && tries < max_tries
      first = self.all(:order => 'RANDOM()', :limit => 1).first
      second = self.all(:order => 'RANDOM()', :limit => 1,
          :conditions => [%{
              (
                  points >= :first_points
                  AND id <> :first_id
              ) OR (
                  id NOT IN (
                      SELECT map_a_id
                      FROM mashes
                      WHERE map_b_id = :first_id
                  )
                  AND id NOT IN (
                      SELECT map_b_id
                      FROM mashes
                      WHERE map_a_id = :first_id
                  )
              )}, {
                :first_id => first.id,
                :first_points => first.points
              }
          ]
      ).first
      tries += 1
    end

    if second.nil?
      logger.error('OH CRAP thar be no more pairings for ye olde mashes')
      [first, first]
    else
      [first, second]
    end
  end

  def self.import(csv_filename)
    FasterCSV.parse(open(csv_filename), :headers => true,
        :header_converters => [:downcase, :symbol]).each do |row|
      map = self.find_or_initialize_by_name("#{row[:city]}, #{row[:region]}")
      map.save
      if block_given?
        yield map
      end
    end
  end

  def self.mashes
    Mash.all(:conditions => ['map_a = :id OR map_b = :id', {:id => self.id}])
  end

  def rounds
    Mash.count(:conditions => ['map_a = :id OR map_b = :id', {:id => self.id}])
  end
end
