#= require ./behavior

class Diagnostic
  basicUrl: settings.baseUrl+'/diagnostic/'

  constructor: (@diagnosticId, @nuclearDiagnostic) ->
    @diagnosticRow = $("#diagnostic-"+diagnosticId)

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

    $.ajax
      type: 'POST'
      url: @basicUrl+action+'/'+@diagnosticId
      success: (html) =>
        @diagnosticRow.replaceWith(html)
        @nuclearDiagnostic.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+'/'+@diagnosticId
      success: (html) =>
        @diagnosticRow.replaceWith(html)
        @nuclearDiagnostic.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+'/'+@diagnosticId
      success: (html) =>
        @diagnosticRow.replaceWith(html)
        @nuclearDiagnostic.nuclearifyAll()
        new FlashMessage('success', 'Gestito').show()
      error: (e) ->
        new FlashMessage('error', e.responseText).show()
        $(sender).removeAttribute('disabled')

class window.NuclearDiagnostic 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 Diagnostic(button.data('diagnostic-id'), self)[action]()
