Control = require './index'
Content = window.require 'core/models/content'
###
  Initialize with {item:{skin instance},attribute:'attribute',options:{options from meta}}
###
class Text extends Control
  template : 'core/views/text'
  className: 'control-text'

  elements:
    'input[type=text]': 'input'

  constructor: ->
    super
    @lengthLimit = @options.lengthLimit or 1000
    if @options.readonly
      @input.attr('readonly', true)
      return
    @input.bind 'input', @_change
    @input.bind 'blur', @onBlur

  render:=>
    super
    @update @item if @item
    @

  update: (item, type, options={}) =>
    value = if item[@attribute]? then item[@attribute] else @options.default
    escaped = @unescapeHtmlEntities value or ''
    return if escaped is @input.val()
    @input.val @unescapeHtmlEntities value or ''

  _change: =>
    @change @htmlEntities @input.val()[...@lengthLimit]

  onBlur: =>
    return if @isDetailInput
    @destroy() if @isContentItem() and !@isNew() and @isEmpty()

  isNew: =>
    return false unless @item
    !@item[@attribute]?

  isEmpty: =>
    return false unless @item
    !@item[@attribute]

  destroy: =>
    @item.destroy()

  isContentItem: =>
    @item instanceof Content

module.exports = Text
