class Easydb4MigrationPlugin.KlosterkammerHannover extends Easydb4MigrationPlugin
	name: ->
		"klosterkammer-hannover"

	init: ->
		# tags from sammlungsobjekte__objs.typus
		@tag_refs_by_name = {}

		# load typus for sammlungsobjekte into cache
		@sammlungsobjekte_typus = {}
		dfr1 = new CUI.Deferred()
		@_migration.query("""
			SELECT
				lk_obj_id AS id,
				typus
			FROM "source.public.sammlungsobjekte__objs"
			WHERE lk_obj_id  IS NOT NULL
			AND   lk_bild_id IS NOT NULL
			AND   typus      IS NOT NULL
			AND   typus      != ''
		""")
		.fail(dfr1.reject)
		.done (result) =>
			for row in result.rows
				@sammlungsobjekte_typus[row.id] = row.typus

				# if the typus is seen for the first time, add it to the map of new tags
				if not @tag_refs_by_name[row.typus]
					ref = row.typus.toLowerCase()
					ref = ref.replace(/[^a-z]/g, '_')
					@tag_refs_by_name[row.typus] = "typus:" + ref

			console.debug "[klosterkammer-hannover]: loaded typus for objs:", result.rows.length, "typus entries"

			dfr1.resolve()
			return

		return dfr1.promise()


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

		if json.import_type == "tags"
			tags_typus = []
			for name, ref of @tag_refs_by_name
				console.debug "[klosterkammer-hannover]: new tag | name:", name, "| reference:", ref
				tags_typus.push
					tag:
						shortname: ref
						reference: ref
						displayname:
							"de-DE": name
						is_default: false
						enabled: true
						displaytype: "search"
						type: "individual"

			json.tags.push
				taggroup:
					shortname: "typus"
					reference: "typus"
					type: "checkbox"
					displayname:
						"de-DE": "Typus"
				_tags: tags_typus

			return

		if json.import_type != "db"
			return

		if json.objecttype != "objs"
			return

		for obj in json.objects
			if not obj["objs"]
				continue
			if not obj["objs"]["__key"]
				continue
			if not @sammlungsobjekte_typus[obj.objs.__key]
				continue
			typus = @sammlungsobjekte_typus[obj.objs.__key]
			tag_ref = @tag_refs_by_name[typus]
			if not tag_ref
				continue
			console.debug "[klosterkammer-hannover]: objs.__key:", obj.objs.__key, "| typus:", typus, "| tag_ref:", tag_ref

			if not obj._tags
				obj._tags = []
			obj._tags.push
				"lookup:_id":
					reference: tag_ref

		return

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