# 
Activator 	= window.require 'spine/controller/activator'
Skin 		= window.require 'core/models/skin'
Scrollable  = require '../../../core/controller/scrollable'
Item 		= require './item'

class PresetList extends Activator
  className		: 'presets-list'
  @include Scrollable
  constructor:->
    super
    @last_scroll = expanded: 0, contracted: 0
    @pending = false
    @state = 'expanded'

    @$bind('changed', @_changed).$bind 'cancel', @_canceled
    @listenTo Skin, 'destroy', @onItemDestroy

    # track the active child
    @$bind 'SkinItem:activate', (_, opts) =>
      @activeChild = opts.item
      @scrollToActive()
    @listenTo Skin, 'create', @scrollToActive

  select: (id, force) =>
    if id
      @activeChild = @children().filter((i)->i.item.id == id)[0]
    else
      @activeChild = @children()[0]

    @activeChild.active {force}

  refresh: (items)=>
    @children (i) -> i.release()
    @append (new Item {item} for item in items)...
    @pending = false
    @delay @refreshScroll, 850
    @

  initSave: ->
    @children((i) -> i.isActive())[0].initSave()

  _changed : (e, changed)=>
    return if @pending

    @pending = true
    @scroll().disable()
    active = @activeChild.el.index()
    scroll_offset = @scroll().offset().top
    @children (child) => child.positionOnChange active, scroll_offset

  _canceled : =>
    return unless @pending

    @pending = false
    @repositionChild()
    @scroll().disable()
    @delay =>
      @refreshScroll()
      @skin = @activeChild.item
      @scrollToActive()
    , 850

  setState: (state) =>
    @last_scroll[@state] = @container?.scrollTop() or 0

    @state = state
    @repositionChild()
    @scroll().disable()
    @delay (=> @scrollToItem @activeChild, @refreshScroll), 750

  scrollToActive: (skin) =>
    return @skin = skin if skin instanceof Skin
    return unless @skin and @skin.id is @activeChild.item.id

    @skin = null
    @scrollToItem @activeChild

  scrollToItem: (item = @activeChild, _callback = ->)=>
    top = (item?.el.get(0).offsetTop + parseInt item?.el.css 'padding-top') or 0
    top = top - (@container.height() - item?.el.height())
    return do _callback unless top > 0
    @container.animate scrollTop: top, 450, _callback

  refreshScroll: (force) =>
    @scroll().enable() if force or !@pending

  repositionChild: (skin) =>
    @children (child) -> child.reposition skin?.destroyed
    @scroll().update()

  onItemDestroy: =>
    @scroll().disable()
    @repositionChild arguments...
    @delay @refreshScroll, 850

module.exports = PresetList
