Controller = window.require 'spine/controller'
textarea = document.createElement 'textarea'

shouldShow = require 'Core/utils/should-show'

class Control extends Controller
  className: "control"
  elements:
    '.control-help': 'helpText'
    '.control-edit-btn input': 'editBtnInput'

  events:
    'input .custom-checkbox-input': 'onEditStateChanged'
    'click .control-upgrade': 'onUpgradeClick'

  constructor: (options) ->
    if !options.isAccesible? then options.isAccesible = true
    super
    @el.attr('data-label', @options.label) if @options.label
    @el.toggleClass('control--restricted', !@isAccesible)
    @render()
    @item?.constructor.bind 'change', @_onChange
    @_onChange @item if @item?
    @initEditableState() if @options.editable

  setItem: (@item) =>
    @_onChange @item

  update: ->

  change: (val, options={}) ->
    return if options.silent

    @item?.updateAttribute @attribute, val, $.extend {@attribute, from: @}, options
    @trigger "change:#{@type or 'control'}", {@attribute, val, value: val}

  _onChange: (item, type, options={}) =>
    return unless item and item.eql @item

    # if the updated changed the item's ID, update the reference
    @item = item if options.changedID
    return @release() if type is 'destroy'
    @el.toggleClass 'control--hidden', !@shouldShow()
    return if options.attribute? and options.attribute isnt @attribute
    @update item, type, options

  shouldShow: -> shouldShow @conditions, @item

  release: =>
    clearTimeout @interval
    @unbind().item?.constructor.unbind 'change', @_onChange
    super
    @

  initEditableState: =>
    @editBtnInput.prop 'checked', !!@item.editedMeta(@attribute)
    @editBtnInput.bind 'change', @onEditStateChanged
    @bind "change:#{@type or 'control'}", @toggleEditState

  toggleEditState: (options) =>
    # return unless options?.attribute is @attribute
    @editBtnInput.prop 'checked', true
    @onEditStateChanged()

  onEditStateChanged: =>
    @item.editedMeta @attribute, @editBtnInput.is ':checked'

  onUpgradeClick: (ev) ->
    ev.preventDefault()
    @$trigger 'Control:upgrade', @options

  render: ->
    super
    @setWindow() if @el.get(0)
    @helpText.attr 'data-tooltip-position': '8% 3%', 'data-tooltip-text': @options.help_text

  setWindow: (window) ->
    @$window = $ @window = window or @el.get(0)?.ownerDocument.defaultView

  htmlEntities: (txt) ->
    textarea.innerHTML = txt
    textarea.innerHTML

  unescapeHtmlEntities: (txt) ->
    textarea.innerHTML = txt
    textarea.innerText || textarea.textContent

module.exports = Control
