#= require ./behavior

class CartographyGate
  constructor: (data, index) ->
    @gate = data.gate
    @alerts = data.alerts
    @index = @computeGateIndex(index)

  getStatus: ->
    if @gate.Status == "ALIVE" then 1 else 0

  getName: ->
    @gate.Descrizione

  computeGateIndex: (index) ->
    _.pad(index.toString(), 2, '0')

  getSctAlarms: ->
    result = {}
    result["CRI#{@index}"] = _(@alerts.alarm).toNumber()
    result["WAR#{@index}"] = _(@alerts.warning).toNumber()
    result["INF#{@index}"] = _(@alerts.info).toNumber()
    result

  toSct: ->

    result = {}
    result["IMP#{@index}"] = @getStatus()
    result["DEN#{@index}"] = @getName()
    _.extend result, @getSctAlarms()


class CartographyGateGroup
  constructor: (@data) ->
    @gateGroup = @data.gateGroup
    @gates = @data.gates

  getLatitude: ->
    @gateGroup.latitude

  getLongitude: ->
    @gateGroup.longitude

  getName: ->
    @gateGroup.name

  getSctGates: ->
    _.values(@gates).map (gateData, index) ->
      new CartographyGate(gateData, index+1).toSct()

  toSct: ->
    result = {}
    result["x"] = _(@getLatitude()).toNumber()
    result["y"] = _(@getLongitude()).toNumber()
    result["denominazione"] = @getName()

    _.extend result, @getSctGates()...


class window.AostaCartography extends window.Behavior

  init: ->
    @map = $("#big-map")
    @thumbnail = $("#small-map")
    @updateLabel = $("#cartography-update-time")
    @sct = @map[0].contentWindow
    @attachThumbnailNavigation()

    @map.load =>
      @startPolling()

  attachThumbnailNavigation: ->
    self = @
    @thumbnail.click (e) ->
      coords = self.getImageCoords(e, @)
      self.sct.ZoomPunto(coords[0], coords[1], 6, "UTM-ED50")

  getImageCoords: (event, img) ->
    posX = (if event.offsetX then (event.offsetX) else event.pageX - img.offsetLeft - 848)
    posY = (if event.offsetY then (event.offsetY) else event.pageY - img.offsetTop - 76)
    @sct.pointConvert(posX, posY)

  fetchData: ->
    $.ajax
      type: "GET"
      url: settings.baseUrl+"/gatesStatus/gateGroupSummary"

  placeMarks: (sctData) ->
    @sct.caricaElementi(sctData)

  refreshTimeLabel: ->
    @updateLabel.html(moment().format('YYYY-MM-DD HH:mm:ss'))

  update: ->
    @fetchData().done (response) =>
      groupsData = JSON.parse(response)
      sctData = _.map groupsData, (groupData) ->
        new CartographyGateGroup(groupData).toSct()
      @placeMarks(sctData)

  startPolling: ->
    @update()

    setInterval =>
      @update()
      @refreshTimeLabel()
    , 5000
