module JamRuby
  class LatencyTester < ActiveRecord::Base

    belongs_to :connection, class_name: 'JamRuby::Connection', foreign_key: :client_id, primary_key: :client_id

    def heartbeat_interval_client
      nil
    end

    def connection_expire_time_client
      nil
    end

    def self.select_latency_tester
      LatencyTester.joins(:connection).first!
    end

    # we need to find that latency_tester with the specified connection (and reconnect it)
    # or bootstrap a new latency_tester
    def self.connect(options)
      client_id = options[:client_id]
      channel_id = options[:channel_id]
      ip_address = options[:ip_address]
      connection_stale_time = options[:connection_stale_time]
      connection_expire_time = options[:connection_expire_time]
      gateway = options[:gateway]

      # first try to find a LatencyTester with that client_id
      latency_tester = LatencyTester.find_by_client_id(client_id)

      if latency_tester
        if latency_tester.connection
          connection = latency_tester.connection
        else
          connection = Connection.new
          connection.client_id = client_id
          latency_tester.connection = connection
        end
      else
        latency_tester = LatencyTester.new
        latency_tester.client_id = client_id
        unless latency_tester.save
          return latency_tester
        end
        connection = Connection.new
        connection.latency_tester = latency_tester
        connection.client_id = client_id
      end

      if ip_address and !ip_address.eql?(connection.ip_address)
        # locidispid stuff
        #addr = JamIsp.ip_to_num(ip_address)
        #isp = JamIsp.lookup(addr)
        #if isp.nil? then ispid = 0 else ispid = isp.coid end
        #block = GeoIpBlocks.lookup(addr)
        #if block.nil? then locid = 0 else locid = block.locid end
        #location = GeoIpLocations.find_by_locid(locid)
        #if location.nil? || isp.nil? || block.nil?
        #  locidispid = nil
        #else
        #  locidispid = locid*1000000+ispid
        #end

        connection.ip_address = ip_address
        #connection.addr = addr
        #connection.locidispid = locidispid
      end

      connection.client_type = 'latency_tester'
      connection.aasm_state = Connection::CONNECT_STATE.to_s
      connection.stale_time = connection_stale_time
      connection.expire_time = connection_expire_time
      connection.as_musician = false
      connection.channel_id = channel_id
      connection.scoring_timeout = Time.now
      connection.gateway = gateway
      unless connection.save
        return connection
      end

      return latency_tester
    end

    def to_s
      client_id
    end
  end
end
