require 'spec_helper'

describe LatencyTester do

  let(:params) {{client_id: 'abc', ip_address: '10.1.1.1', connection_stale_time:40, connection_expire_time:60, channel_id: '1', gateway: 'gateway1'} }

  before {
    pending "Latency Tester removed from production"
  }

  it "success" do
    latency_tester = FactoryGirl.create(:latency_tester)
    latency_tester.connection.should_not be_nil
    latency_tester.connection.latency_tester.should_not be_nil

  end

  describe "connect" do
    it "no existing latency tester" do
      latency_tester = LatencyTester.connect(params)
      latency_tester.errors.any?.should be_false
      latency_tester.connection.ip_address.should == params[:ip_address]
      latency_tester.connection.stale_time.should == params[:connection_stale_time]
      latency_tester.connection.expire_time.should == params[:connection_expire_time]
    end

    it "existing latency tester, no connection" do
      latency_tester = FactoryGirl.create(:latency_tester, client_id: params[:client_id], make_connection: false)
      latency_tester.connection.should be_nil

      latency_tester.client_id = params[:client_id]
      latency_tester.save!

      found = LatencyTester.connect(params)
      found.should == latency_tester
      found.connection.should_not be_nil
      found.connection.aasm_state.should == Connection::CONNECT_STATE.to_s
      found.connection.client_id.should == latency_tester.client_id
    end

    it "existing latency tester, existing connection" do
      latency_tester = FactoryGirl.create(:latency_tester)

      latency_tester.connection.aasm_state = Connection::STALE_STATE.to_s
      latency_tester.save!
      set_updated_at(latency_tester.connection, 6.hours.ago)

      params[:client_id] = latency_tester.connection.client_id

      found = LatencyTester.connect(params)
      found.should == latency_tester
      found.connection.should == latency_tester.connection
      # state should have refreshed from stale to connected
      found.connection.aasm_state.should == Connection::CONNECT_STATE.to_s
      # updated_at needs to be poked on connection to keep stale non-stale
      (found.connection.updated_at - latency_tester.connection.updated_at).to_i.should == 60 * 60 * 6 # 6hours
    end
  end
end
