delegate = require('dom-delegate')
_ = require('lodash')

METRICS_PREFIX = "EXPL"
METRICS_URL    = "http://metrics.aviasales.ru"

send_metric = (params = {}) ->
  params["rand"] = Math.random()
  params_string = ("#{key}=#{value}" for key, value of params).join('&')
  url = "#{METRICS_URL}/?#{params_string}"
  img = new Image()
  img.setAttribute("src", url)

reach_metric_goal = (goal_name, data, count = null) ->
  goal_name = "#{METRICS_PREFIX}_#{goal_name}"
  send_metric({
    "goal": goal_name,
    "data": if _.isUndefined(data) or _.isNull(data) then "" else JSON.stringify(data)
    "count": if _.isUndefined(count) or _.isNull(count) then "" else count
  })

init = ->
  metrics_delegate = delegate(document.body)
  metrics_delegate.on("click", "[metric]", (event, target) ->
    dataset = {}
    for { name, value } in target.attributes when name.substring(0, 4) is 'data'
      dataset[name.substring(5)] = value
    reach_metric_goal(target.getAttribute("metric"), dataset)
  )


module.exports =
  init: init
  reach_goal: reach_metric_goal
  send_metric: send_metric
