module JamRuby

  def strip_quotes str
    return nil if str.nil?

    if str.start_with? '"'
      str = str[1..-1]
    end

    if str.end_with? '"'
      str = str.chop
    end

    return str
  end

  # creates messages (implementation: protocol buffer) objects cleanly
  class Database

    @@log = Logging.logger[Database]

    #def self.db_timezone
    #  @@db_timezone ||= TZInfo::Timezone.get(fetch_db_timezone)
    #end

    def self.db_timezone
      @@db_timezone ||= ActiveSupport::TimeZone.new(fetch_db_timezone)
    end

    def self.fetch_db_timezone
      result = ActiveRecord::Base.connection.execute('show timezone')
      tz = result.getvalue(0, 0)
      result.clear
      tz
    end

    def self.copy(table_name, file)
      @@log.debug("issuing COPY to #{table_name} from #{file}")

      raw  = GeoIpBlocks.connection.raw_connection

      result = raw.copy_data "COPY #{table_name} FROM STDIN" do
        File.open(file, 'r').each do |line|
          raw.put_copy_data line
        end
      end

      count = GeoIpBlocks.connection.select_value("select count(*) from #{table_name}").to_i
      ActiveRecord::Base.logger.debug "loaded #{count} records into #{table_name}"
    end

    def self.copy_table(table_name)
      copied_name = "#{table_name}_copied"
      GeoIpBlocks.connection.execute "CREATE TABLE #{copied_name} (LIKE #{table_name} INCLUDING DEFAULTS INCLUDING CONSTRAINTS INCLUDING COMMENTS INCLUDING STORAGE)"
      copied_name
    end

    def self.dump(query)
      result = ActiveRecord::Base.connection.execute(query)
      fields = result.fields
      header = ""
      fields.each do |field|
        header << field
        header << ', '
      end
      header = header[0..header.length - 3]
      puts header

      result.each do |row|
        row_out = ''
        fields.each do |field|
            if row[field].nil?
              row_out << 'NULL'
            else
              if block_given?
                row_out << yield(field, row[field]).to_s
              else
                row_out << row[field].to_s
              end
            end
          row_out << ', '
        end
        row_out = row_out[0..row_out.length - 3]
        puts row_out
      end
    end
  end
end