#= require ./behavior

class EventReporting
  basicUrl: settings.baseUrl+'/alert/'

  constructor: (@eventReportingId, @nuclearAlert) ->
    @eventReportingRow = $("#eventreporting-"+@eventReportingId)

  takeCharge: (sender)->
    action = 'takeCharge'
    $(sender).attr('disabled', 'disabled')

    $.ajax
      type: 'POST'
      url: @basicUrl+action+'/'+@eventReportingId
      success: (html) =>
        @eventReportingRow.replaceWith(html)
        @nuclearAlert.nuclearifyAll()
        new FlashMessage('success', 'Preso in carico').show()
      error: (e) ->
        new FlashMessage('error', e.responseText).show()
        $(sender).removeAttribute('disable')

  releaseCharge: (sender) ->
    action = 'releaseCharge'
    $(sender).attr('disabled', 'disabled')

    $.ajax
      type: 'POST'
      url: @basicUrl+action+'/'+@eventReportingId
      success: (html) =>
        @eventReportingRow.replaceWith(html)
        @nuclearAlert.nuclearifyAll()
        new FlashMessage('success', 'Rilasciato').show()
      error: (e) ->
        new FlashMessage('error', e.responseText).show()
        $(sender).removeAttribute('disabled')

  manage: (sender) ->
    action = 'manage'
    $(sender).attr('disabled', 'disabled')

    $.ajax
      type: 'POST'
      url: @basicUrl+action+'/'+@eventReportingId
      success: (html) =>
        @eventReportingRow.replaceWith(html)
        @nuclearAlert.nuclearifyAll()
        new FlashMessage('success', 'Gestito').show()
      error: (e) ->
        new FlashMessage('error', e.responseText).show()
        $(sender).removeAttribute('disabled')

class window.NuclearAlert extends window.Behavior
  init: ->
    @nuclearifyAll()

  nuclearifyAll: ->
    @nuclearifyButton('take-charge', 'takeCharge')
    @nuclearifyButton('release-charge', 'releaseCharge')
    @nuclearifyButton('manage', 'manage')

  nuclearifyButton: (buttonClass, action) ->
    self = @
    $(".#{buttonClass}[data-nuclear-botton!=nuclear]").each ->
      button = $(this)
      button.nuclear
        alertText: button.data('confirm-text')
        delay: 0
        useOnce: true
        onClick: ->
          new EventReporting(button.data('eventreporting-id'), self)[action]()
