class BaseMigrationNodePresetContext extends BaseMigrationNodeData

	initOpts: ->
		super()
		@addOpts
			context:
				mandatory: true

	getDisplayText: ->
		$$("acl.rights.context.#{@_context}")

	getActionPane: ->
		pane = @getActionPaneBase()
		pane

	checkMigrateButton: ->
		@__migrateBtn.enable()

	getActionFields: ->
		[
			type: CUI.Output
			form:
				label: $$("base.migration.node.presets.text")
			text: @getDisplayText()
		,
			type: CUI.Options
			name: "mode"
			radio: true
			form:
				label: $$("base.migration.common.options")
			options: [
				text: $$("base.migration.common.replace")
				value: "replace"
			,
				text: $$("base.migration.common.add")
				value: "add"
			]
		]

	migrate: (ev, actionData) ->
		position = if actionData.mode == "add" then @getNextPresetPosition() else 0

		presets = []
		for child in @children
			presets.push(child.getPreset(position))
			position++

		# If the mode is add, the presets are saved directly. If not, the old presets are removed first.
		if actionData.mode == "add"
			return @savePresets(presets)
		else
			deferred = new CUI.Deferred()
			@deleteCurrentPresets().done( =>
				@savePresets(presets).done(deferred.resolve).fail(deferred.reject)
			).fail(deferred.reject)
			return deferred.promise()

	getNextPresetPosition: () ->
		presets = @getMigration().getBaseData().preset[@_context] or []
		return (presets[presets.length - 1]?.right_preset._position + 1) or 0

	savePresets: (presets) ->
		@log($$("base.migration.console.log.presets.saving.md",
			count: presets.length
			context: @getDisplayText()
		))

		ez5.api.right(
			type: "POST"
			api: "/#{@_context}/presets"
			json_data: presets
		).done( =>
			@log($$("base.migration.console.log.presets.migrated.md",
				count: presets.length
				context: @getDisplayText()
			))
		).fail( =>
			@log($$("base.migration.console.log.presets.saving-failed.md",
				count: presets.length
				context: @getDisplayText()
			))
		)

	deleteCurrentPresets: ->
		deletePromises = []
		presets = @getMigration().getBaseData().preset[@_context] or []

		@log($$("base.migration.console.log.presets.removing.md",
			count: presets.length
			context: @getDisplayText()
		))
		for preset in presets
			deletePromises.push(@__deletePreset(preset))

		return CUI.when(deletePromises).done( =>
			@log($$("base.migration.console.log.presets.removed.md",
				count: presets.length
				context: @getDisplayText()
			))
		).fail( =>
			@log($$("base.migration.console.log.presets.removing-failed.md",
				count: presets.length
				context: @getDisplayText()
			))
		)

	__deletePreset: (preset) ->
		id = preset.right_preset._id
		ez5.api.right(
			type: "DELETE"
			api: "/#{@_context}/presets/#{id}"
		)
