

Model       = window.require 'spine/model'
AjaxMixin   = require '../../api/mixin'
Helper      = window.require 'spine/utils/helper'
isArray     = Helper.isArray

defaultAtts = ["name","user_id",'uses',"metas","widget_id"]

class Skin extends Model
	@extend AjaxMixin
	@configure('Skin')

	@change AjaxMixin.ajaxChange

	@meta: (widget_id) -> (require './widget').find(widget_id).skinMeta

	# Used by Model.sort
	# Sorts the presets to the top and the user skins to the bottom
	# @comparator: (a, b) ->
	# 	+b.isPreset() - +a.isPreset()

	constructor:(atts={})->
		# for attr of (mattr = @constructor.meta.attributes) when (!atts[attr]? and mattr[attr]?)
		# 	atts[attr] = mattr[attr].options.default
		atts.name or= 'Untitled Theme'
		atts.uses or= 0
		atts.metas or= {}
		super(atts)

	attributes: ->
		attributes = defaultAtts.slice(0)
		try
			tabs = @constructor.meta(@widget_id).tabs
			throw new Error("Widget[#{ @widget_id }].tabs is not loaded.") unless tabs
			meta_props = ($.extend {}, atts for tab,atts of tabs)
			meta_attributes = $.extend {}, meta_props...
			attributes.push (key for key,value of meta_attributes)...
		catch
			attributes = Object.keys(@)
			if Object.getPrototypeOf(@) instanceof Skin
				attributes = $.extend [], attributes, Object.keys(Object.getPrototypeOf(@))

		result = {}
		for key in attributes when key of this
			if typeof @[key] isnt 'function'
				result[key] = @[key]
		result.id = @id if @id
		result

	used:(inc=-1) ->
		@updateAttribute('uses', Math.max((@uses>>0)+inc,0),{used:true})

	updateAttributes: (atts, options={}) ->
		options.ajax = false
		super

	changeID: (id) ->
		Composition = require './composition' # prevent circular dependency
		oldId = @id
		super
		comps = Composition.findAllByAttribute('skin_id', oldId)
		comps.forEach((comp) => comp.updateAttribute('skin_id', @id))

		@used(comps.length)

	freeze:->
		@original = @attributes()
		@original.id = null
		delete @original.uses
		delete @original.id

	reset: ->
		@updateAttributes @original,{ajax: false}

	isPersisted: ->
		return false unless @id
		return @id.slice(0, 1) isnt 'c'

	isPreset: ->
		return !@user_id

	persist: ->
		if @isPersisted()
			promise = @ajax().update()
		else
			promise = @ajax().create()

		return promise

module.exports = Skin
