#= require jquery
#= require jquery_ujs
#= require typeahead.bundle
#= require bootstrap
#= require select2
#= require json2
#= require jquery.json-editor
#= require latlon_and_geo
#= require spectrum
#= require ./worker-checker
#= require_self

window.setupJsonEditor = ($editors = $(".live-json-editor")) ->
  JSONEditor.prototype.ADD_IMG = '<%= image_path 'json-editor/add.png' %>'
  JSONEditor.prototype.DELETE_IMG = '<%= image_path 'json-editor/delete.png' %>'
  editors = []
  $editors.each ->
    $editor = $(this)
    jsonEditor = new JSONEditor($editor, $editor.data('width') || 400, $editor.data('height') || 500)
    jsonEditor.doTruncation true
    jsonEditor.showFunctionButtons()
    editors.push jsonEditor
  return editors

hideSchedule = ->
  $(".schedule-region .can-be-scheduled").hide()
  $(".schedule-region .cannot-be-scheduled").show()

showSchedule = (defaultSchedule = null) ->
  if defaultSchedule?
    $(".schedule-region select").val(defaultSchedule).change()
  $(".schedule-region .can-be-scheduled").show()
  $(".schedule-region .cannot-be-scheduled").hide()

hideLinks = ->
  $(".link-region .select2-container").hide()
  $(".link-region .propagate-immediately").hide()
  $(".link-region .cannot-receive-events").show()

showLinks = ->
  $(".link-region .select2-container").show()
  $(".link-region .propagate-immediately").show()
  $(".link-region .cannot-receive-events").hide()
  showEventDescriptions()

hideControlLinks = ->
  $(".control-link-region").hide()

showControlLinks = ->
  $(".control-link-region").show()

hideEventCreation = ->
  $(".event-related-region").hide()

showEventCreation = ->
  $(".event-related-region").show()

showEventDescriptions = ->
  if $("#agent_source_ids").val()
    $.getJSON "/agents/event_descriptions", { ids: $("#agent_source_ids").val().join(",") }, (json) =>
      if json.description_html?
        $(".event-descriptions").show().html(json.description_html)
      else
        $(".event-descriptions").hide()
  else
    $(".event-descriptions").html("").hide()

$(document).ready ->
  $('.navbar .dropdown.dropdown-hover').hover \
    -> $(this).addClass('open'),
    -> $(this).removeClass('open')

  # JSON Editor
  window.jsonEditor = setupJsonEditor()[0]

  # Flash
  if $(".flash").length
    setTimeout((-> $(".flash").slideUp(-> $(".flash").remove())), 5000)

  # Help popovers
  $('.hover-help').popover(trigger: 'hover', html: true)

  # Agent Navigation
  $agentNavigate = $('#agent-navigate')

  # initialize typeahead listener
  $agentNavigate.bind "typeahead:selected", (event, object, name) ->
    item = object['value']
    $agentNavigate.typeahead('val', '')
    if agentPaths[item]
      $(".spinner").show()
      navigationData = agentPaths[item]
      if !(navigationData instanceof Object) || !navigationData.method || navigationData.method == 'GET'
        window.location = navigationData.url || navigationData
      else
        $("<a href='#{navigationData.url}' data-method='#{navigationData.method}'></a>").appendTo($("body")).click()

  # substring matcher for typeahead
  substringMatcher = (strings)->
    findMatches = (query, callback) ->
      matches = []
      substrRegex = new RegExp(query, "i")
      $.each strings, (i, str) ->
        matches.push value: str  if substrRegex.test(str)
      callback(matches.slice(0,6))

  $agentNavigate.typeahead
    minLength: 1,
    highlight: true,
  ,
    source: substringMatcher(agentNames)


  # Pressing '/' selects the search box.
  $("body").on "keypress", (e) ->
    if e.keyCode == 47 # The '/' key
      if e.target.nodeName == "BODY"
        e.preventDefault()
        $agentNavigate.focus()

  # Agent Show
  fetchLogs = (e) ->
    agentId = $(e.target).closest("[data-agent-id]").data("agent-id")
    e.preventDefault()
    $("#logs .spinner").show()
    $("#logs .refresh, #logs .clear").hide()
    $.get "/agents/#{agentId}/logs", (html) =>
      $("#logs .logs").html html
      $("#logs .spinner").stop(true, true).fadeOut ->
        $("#logs .refresh, #logs .clear").show()

  clearLogs = (e) ->
    if confirm("Are you sure you want to clear all logs for this Agent?")
      agentId = $(e.target).closest("[data-agent-id]").data("agent-id")
      e.preventDefault()
      $("#logs .spinner").show()
      $("#logs .refresh, #logs .clear").hide()
      $.post "/agents/#{agentId}/logs/clear", { "_method": "DELETE" }, (html) =>
        $("#logs .logs").html html
        $("#show-tabs li a.recent-errors").removeClass 'recent-errors'
        $("#logs .spinner").stop(true, true).fadeOut ->
          $("#logs .refresh, #logs .clear").show()

  $(".agent-show #show-tabs a[href='#logs'], #logs .refresh").on "click", fetchLogs
  $(".agent-show #logs .clear").on "click", clearLogs

  if tab = window.location.href.match(/tab=(\w+)\b/i)?[1]
    if tab in ["details", "logs"]
      $(".agent-show .nav-pills li a[href='##{tab}']").click()

  # Editing Agents
  $("#agent_source_ids").on "change", showEventDescriptions

  $("#agent_type").on "change", ->
    if window.jsonEditor?
      $("#agent-spinner").fadeIn();
      $("#agent_source_ids").select2("val", {});
      $(".event-descriptions").html("").hide()
      $.getJSON "/agents/type_details", { type: $(@).val() }, (json) =>
        if json.can_be_scheduled
          showSchedule(json.default_schedule)
        else
          hideSchedule()

        if json.can_receive_events
          showLinks()
        else
          hideLinks()

        if json.can_control_other_agents
          showControlLinks()
        else
          hideControlLinks()

        if json.can_create_events
          showEventCreation()
        else
          hideEventCreation()

        $(".description").html(json.description_html) if json.description_html?

        $('.oauthable-form').html(json.form) if json.form?

        if $("#agent_options").hasClass("showing-default") || $("#agent_options").val().match(/\A\s*(\{\s*\}|)\s*\Z/g)
          window.jsonEditor.json = json.options
          window.jsonEditor.rebuild()

        $("#agent-spinner").stop(true, true).fadeOut();

  $("#agent_type").change() if $("#agent_type").length

  # Select2 Selects
  $(".select2").select2(width: 'resolve')

  if $(".schedule-region")
    if $(".schedule-region").data("can-be-scheduled") == true
      showSchedule()
    else
      hideSchedule()

  if $(".link-region")
    if $(".link-region").data("can-receive-events") == true
      showLinks()
    else
      hideLinks()

  if $(".control-link-region")
    if $(".control-link-region").data("can-control-other-agents") == true
      showControlLinks()
    else
      hideControlLinks()

  if $(".event-related-region")
    if $(".event-related-region").data("can-create-events") == true
      showEventCreation()
    else
      hideEventCreation()
