class Easydb4Migration.Rgzm extends Easydb4MigrationPlugin
	name: ->
		"rgzm"

	init: ->
		@sys_by_ref = systematik: {}
		@__itemtyp = {}
		@editmask_by_ref = {}
		@first_item_idx = undefined

		dfr = new CUI.Deferred()

		@_migration.query('SELECT * FROM "source.rgzm.itemtyp"')
		.fail(dfr.reject)
		.done (result) =>
			for row in result.rows
				@__itemtyp["itemtyp:"+row[0]] = row

			@_migration.query("""
			SELECT 'item:'||a.id AS reference, b.editmask
			  FROM "source.rgzm.item" a
			  LEFT JOIN "source.rgzm.itemtyp" b ON (a.lk_itemtyp = b.id)
			""")
			.fail(dfr.reject)
			.done (result) =>
				for row in result.rows
					@editmask_by_ref[row.reference] = row.editmask
				console.debug "editmask_by_ref", @editmask_by_ref
				dfr.resolve()
				return

			return

		return dfr.promise()

	copy_sys: (new_target, ref) ->
		source_sys = @sys_by_ref.systematik[ref]

		# console.debug "copy sys:", new_target, ref, source_sys
		if not source_sys
			@_migration.logerror("Could not find systematik with reference: "+ref+". Skipping.")
			return

		if not @sys_by_ref[new_target]
			@sys_by_ref[new_target] = {}

		if @sys_by_ref[new_target][ref]
			return

		@sys_by_ref[new_target][ref] = source_sys
		if source_sys.systematik["lookup:_id_parent"]
			# copy parent into the same sys tree
			@copy_sys(new_target, source_sys.systematik["lookup:_id_parent"].easydb4_reference)
		return


	map_typ_sys:
		# raeumlich
		# typ:1, typ:2, typ:3, typ:7, typ:9, typ:17, typ:18
		1: "raeumlich"
		2: "raeumlich"
		3: "raeumlich"
		7: "raeumlich"
		9: "raeumlich"
		17: "raeumlich"
		18: "raeumlich"

		# material2
		# typ:32
		32: "material_standard"

		# objekttyp
		# typ:33
		33: "objekttyp"

		# technik
		# typ:34
		34: "technik"

		# zeitlich_einordnung
		# typ:10, typ:6
		6: "zeitlich_einordnung"
		10: "zeitlich_einordnung"

		# verwahrorte
		# typ:4
		4: "verwahrorte"

		# rgzm_intern
		# typ:5, typ:13, typ:15, typ:16, typ:19, typ:20, typ:21,
		# typ:23, typ:24, typ:28, typ:29, typ:21, typ:35, typ:36, typ:37, typ:38
		5: "rgzm_intern"
		13: "rgzm_intern"
		15: "rgzm_intern"
		16: "rgzm_intern"
		19: "rgzm_intern"
		20: "rgzm_intern"
		21: "rgzm_intern"
		23: "rgzm_intern"
		24: "rgzm_intern"
		28: "rgzm_intern"
		29: "rgzm_intern"
		21: "rgzm_intern"
		31: "rgzm_intern"
		35: "rgzm_intern"
		36: "rgzm_intern"
		37: "rgzm_intern"
		38: "rgzm_intern"

		# publikationen
		# typ:11, typ:8
		8: "publikationen"
		11: "publikationen"

	map_nested_filter:
		"_nested:item__item_objekt_1364": "ItemEdit_Objekt"
		"_nested:item__item_werkblatt_1409": "ItemEdit_Werkblatt"
		# "_nested:item__item_1411": "ItemEdit_Foto"
		"_nested:item__item_foto_1510": "ItemEdit_Foto"


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

		# console.debug "post process paylaod:", filename, json

		if json.objecttype == "systematik"
			for obj in json.objects
				@sys_by_ref.systematik[obj.systematik.easydb4_reference] = obj

		if json.objecttype == "item"

			if @first_item_idx == undefined
				@first_item_idx = filename_idx

			# checks all keys in the map
			find_sys = (item) =>
				for k, v of item
					if CUI.util.isArray(v)
						for item2 in v
							find_sys(item2)
						continue

					if item[k+":source_name"] == "systematik"
						# this key needs to be pushed into the new tree
						@copy_sys(v._objecttype, v[v._objecttype]["lookup:_id"].easydb4_reference)

				return

			nested_map_keys = Object.keys(@map_nested_filter)

			for obj in json.objects
				pool_ref = obj.item._pool.pool["lookup:_id"].reference
				itemtyp = @__itemtyp[pool_ref]

				nummer = obj.item.nummer

				if nummer
					# add pool praefix to nummer

					delete(obj.item.nummer)
					if itemtyp.praefix
						nummer = itemtyp.praefix + nummer

					# if old_pool.editmask == "ItemEdit_Objekt"
					# 	obj.item.nummer_objekt = nummer
					# else
					obj.item.nummer = nummer

					# console.debug "obj:", nummer, obj, pool_ref, old_pool

				# remove self-referencing links, see #54558
				for k, v of obj.item
					if not k.startsWith("_nested:item__item_item")
						continue

					CUI.util.removeFromArray(null, (v), (v) =>
						if not obj.item.easydb4_reference
							return false
						if v.lk_item_to?.item?["lookup:_id"]?.easydb4_reference == obj.item.easydb4_reference
							@_migration.logwarn("Removing self-referencing "+k+": "+obj.item.easydb4_reference)
							return true
						return false
					)


				find_sys(obj.item)
				for k, v of obj.item

					if k == "_version" and v == 2
						# this means we are updating
						# use group mode for updates

						delete(obj.item[k])
						# group mode for the json importer
						obj.item["_version:auto_increment"] = true

					# set nested replace strategies for group_mode
					if k.startsWith("_nested:")
						if k == "_nested:item__item_item"
							obj.item[k+":group_mode"] = "append"
						else
							obj.item[k+":group_mode"] = "replace"

					if k == "express_lk_to_id" # copy this into nested
						obj.item["_nested:item__express_lk_to_id_neu"] = [
							express_lk_to_id: v
						]

					if k == "_nested:item__datatree_old"
						for item in v
							if not item.cat_id
								continue

							sys_link = CUI.util.copyObject(item.cat_id, true)

							ref = sys_link.systematik?["lookup:_id"]?.easydb4_reference
							if not ref
								continue

							sys_entry = @sys_by_ref.systematik[ref]
							typ = sys_entry.systematik.lk_typ.typ["lookup:_id"].easydb4_reference.substr(4) # cut off typ

							new_sys = @map_typ_sys[typ]
							if not new_sys
								warn = "Unknown systematik typ: "+typ+". Skipping."
								@_migration.logwarn(warn)
								continue

							@copy_sys("systematik_"+new_sys, ref)

							sys_link._objecttype = "systematik_"+new_sys
							sys_link[sys_link._objecttype] = sys_link.systematik
							delete(sys_link.systematik)

							nes_key = "_nested:item__"+sys_link._objecttype

							if not obj.item[nes_key]
								obj.item[nes_key] = []
								obj.item[nes_key+":group_mode"] = "replace"

							obj.item[nes_key].push
								lk_systematik_id: sys_link

							# console.debug "nested item:", k, v, sys_entry, sys_link, new_sys

		if filename == "basetype_user_ldap_sso.json" # last payload

			payload_idx = @first_item_idx

			for new_ot, sys_entries of @sys_by_ref
				if new_ot == "systematik"
					continue

				objects = []

				for ref, sys_entry of sys_entries
					new_entry = CUI.util.copyObject(sys_entry, true)
					new_entry[new_ot] = new_entry[new_entry._objecttype]
					delete(new_entry[new_entry._objecttype])
					new_entry._objecttype = new_ot

					objects.push(new_entry)

				objects.sort (a, b) ->
					if a._depth < b._depth
						return -1
					else if a._depth > b._depth
						return 1
					else
						return 0

				new_json = null

				init_json = =>
					new_json =
						import_type: "db"
						objecttype: new_ot
						objects: []

				init_json()

				for obj, idx in objects
					new_json.objects.push(obj)
					if idx == objects.length-1 or objects[idx+1]._depth > obj._depth
						# next is bigger, write out
						fn = new_ot+"-"+obj._depth+".json"
						# console.debug "new json:", fn, payload_idx, @first_item_idx
						store_file(fn, new_json, payload_idx)
						payload_idx++
						init_json()


		return


ez5.session_ready =>
	Easydb4Migration.plugins.registerPlugin(Easydb4Migration.Rgzm)


# if k in nested_map_keys
# 	keep_items = []
# 	for item in v
# 		link_to_item = item.lk_item_to?.item["lookup:_id"]
# 		# console.debug "linked_to_item:", link_to_item, item
# 		if not link_to_item
# 			warn = "Keeping empty nested "+k+": "+obj.item.easydb4_reference
# 			@_migration.logwarn(warn)
# 			item.__post_process_warning = warn
# 			keep_items.push(item)
# 			continue

# 		editmask = @editmask_by_ref[link_to_item.easydb4_reference]
# 		if not editmask
# 			warn = "Keeping item in nested. Reference not found: "+k+": "+obj.item.easydb4_reference+" Linked:"+link_to_item.easydb4_reference
# 			@_migration.logwarn(warn)
# 			item.__post_process_warning = warn
# 			keep_items.push(item)
# 			continue

# 		if editmask == @map_nested_filter[k]
# 			# console.debug("Object:", obj.item.easydb4_reference, "Filter IN", link_to_item.easydb4_reference, "from", k)
# 			item.__post_process_notice = "Item OK with editmask "+editmask+" in nested "+k+": "+obj.item.easydb4_reference+" Linked: "+link_to_item.easydb4_reference
# 			keep_items.push(item)
# 		else
# 			info = "Removing item with editmask "+editmask+" in nested "+k+": "+obj.item.easydb4_reference+" Linked: "+link_to_item.easydb4_reference
# 			@_migration.loginfo(info)
# 			; # console.debug("Object:", obj.item.easydb4_reference, "Filter OUT", link_to_item.easydb4_reference, "from", k)
# 		# console.debug "itemtyp:", itemtyp
# 		#
# 	# console.debug("Overwriting item:", obj.item, "key:", k, "from:", v, "with:", keep_items)
# 	obj.item[k] = keep_items
