xhr = require('xhr')
metrics = require('./metrics.coffee')
_ = require('lodash')
dispatcher = require('./dispatcher')

do_measure_speed = Math.random() < 0.05 && localStorage.getItem('inter_checked') != 'true'
if do_measure_speed
  localStorage.setItem('inter_checked', 'true')
statistics = {}

hosts_map = {
  'skyscanner.ru': 'http://images.skyscnr.com/images/country/flag/header/ru.png',
  'momondo.ru': 'http://cdn1.momondo.net/i-3/images/sprites/flights-120822-2.png',
  'kayak.com': 'http://www.kayak.com/favicon.ico',
  'kayak.ru': 'http://www.kayak.ru/favicon.ico',
  'onetwotrip.ru': 'https://www.onetwotrip.com/images/seo/ico_loop.png'
}

is_from_cache = (img) ->
  _.any([img.naturalWidth, img.naturalHeight, img.width, img.height, img.complete], Boolean)

send_data = _.after(_.keys(hosts_map).length, ->
  metrics.reach_goal('USERS_INTERSECTION', statistics)
)

measure_load_speed = (url, label) ->
  start = performance.now()
  img = document.createElement("img")
  measure_speed = ->
    end = performance.now()
    diff = end - start
    statistics[label] = diff < 50 || statistics[label]
    send_data()

  img.onload = measure_speed
  img.onerror = send_data
  img.src = url

  statistics[label] = is_from_cache(img)
  true
if do_measure_speed
  dispatcher.on('components_loaded', ->
    setTimeout(->
      _.forEach(hosts_map, measure_load_speed)
    , 5000)
  )
