class Easydb4MigrationPlugin.UniStuttgart extends Easydb4MigrationPlugin
	name: ->
		"uni-stuttgart"

	init: ->
		@pool_map = {}
		dfr = new CUI.Deferred()

		@_migration.query("""
			SELECT id, name
			FROM "source.public.pool"
		""")
		.fail(dfr.reject)
		.done (result) =>
			for row in result.rows
				@pool_map[row[0]] = row[1]

			dfr.resolve()

		return dfr.promise()

	tagref: (pool_id) ->
		return "tag:" + pool_id

	payload: (filename, json, update, store_file) ->

		# tags from pool names
		if json.import_type == "tags"

			tags = []
			for pool_id, pool_name of @pool_map
				console.debug @name(), "tag:", @tagref(pool_id), "name:", pool_name
				tags.push
					tag:
						reference: @tagref(pool_id)
						displayname:
							"de-DE": pool_name
						is_default: false
						enabled: true
						displaytype: "search"
						type: "individual"

			json.tags.push
				taggroup:
					reference: "easydb4:pools"
					type: "choice"
					displayname:
						"de-DE": "easydb4 Pools"
				_tags: tags

			return

		if json.import_type != "db"
			return

		if json.objecttype != "bilder"
			return

		# collect all object keys
		obj_ids=[]

		for obj in json.objects
			if obj.bilder.__key
				obj_ids.push(obj.bilder.__key)

		# collect all pool ids for the object keys
		sql = """
			SELECT id, pool_id
			FROM "source.public.bilder"
			WHERE id IN ( """ + obj_ids.join(", ") + """ ) """

		dfr = new CUI.Deferred()
		@_migration.query(sql)
		.fail(dfr.reject)
		.done (result) =>
			obj_id_map={}
			for row in result.rows
				obj_id_map[row[0]] = row[1]

			# iterate over the objects again and add tags based on pool ids
			for obj in json.objects
				if not obj.bilder.__key
					continue

				if not obj_id_map[obj.bilder.__key]
					continue

				pool_id = obj_id_map[obj.bilder.__key]
				if not @pool_map[pool_id]
					continue

				if not obj._tags
					obj._tags = []

				obj._tags.push
					"lookup:_id":
						reference: @tagref(pool_id)

			dfr.resolve()

		return dfr.promise()


ez5.session_ready =>
	Easydb4Migration.plugins.registerPlugin(Easydb4MigrationPlugin.UniStuttgart)
