class Easydb4Migration.SyrianHeritage extends Easydb4MigrationPlugin
	name: ->
		"syrian-heritage"

	payload: (filename, json, update) ->

		# replace all "externe quelle with link
		#
		@_migration.query('SELECT * FROM "source.public.externe_quellen"')
		.done (result) =>

			ext_by_id = {}

			for row in result.rows
				ext_by_id["externe_quellen:"+row.id] = row

			repl_ext_quelle = (data) =>
				for k, v of data
					if CUI.util.isArray(v)
						for item in v
							repl_ext_quelle(item)
						continue

					if CUI.util.isPlainObject(v)
						repl_ext_quelle(v)
						continue

					if k.endsWith(":source_name") and v == "externe_quellen"
						ext_quelle = ext_by_id[data.lk_externe_quelle_id.externe_quellen["lookup:_id"].easydb4_reference]

						if ext_quelle.url.endsWith("/")
							if data.name?.startsWith("/")
								_url = ext_quelle.url+data.name.substr(1)
							else
								_url = ext_quelle.url+(data.name or "")
						else
							_url = ext_quelle.url+"/"+(data.name or "")

						url =
							url: _url
							text_plain: ext_quelle.name
							_standard: {}

						data.url = url

						url._standard.text = url.text or url.url

						url._fulltext =
							text: ext_quelle.name
							string: data.url.url

						location = CUI.parseLocation(url.url)

						if location
							hostnameParts = location.hostname.split(".")
							url.tld = hostnameParts[hostnameParts.length - 1]
							url.hostname = location.hostname
						else
							url.tld = ""
							url.hostname = ""

						# url: url
						# hostname: location.hostname
						# tld: hostnameParts[hostnameParts.length - 1]
						# text: text
						# text_plain: text_plain
						# datetime: cdata.datetime
						# _fulltext:
						# 	l10ntext: text
						# 	text: text_plain
						# 	string: url
						# _standard: standard


						# console.warn "URL: ", json.objecttype, url.url

				return

			repl_ext_quelle(json)


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