class Easydb4Migration.UnibZuerich extends Easydb4MigrationPlugin

	name: ->
		"unib-zuerich"

	payload: (filename, json, update) ->
		if json.objecttype != "bilder"
			return

		fn = @_migration.getFileRootUrl()+'bildcode_mapping.csv'

		console.debug "payload:", json
		dfr = new CUI.Deferred()

		connect = new CUI.XHR
			responseType: "text"
			url: fn
		connect.start()
		.done (data) =>
			console.debug "recevied data", data, filename, json, update, arguments, connect.getXHR()
			csv = new CUI.CSVData()
			csv.parse(text: data, defer: false)

			filename_by_bildcode = {}

			for row in csv.getRows()
				filename_by_bildcode[row[0]] = encodeURI(row[1].replace("/mnt/Bildarchiv/", "http://localhost/bildarchiv/"))

			for obj in json.objects
				bild_fn = filename_by_bildcode[obj.bilder.unique_identifier]
				if not bild_fn
					@_migration.loginfo("Bildcode '"+obj.bilder.unique_identifier+"' not found in CSV. Skipping.")
					continue

				if not obj.bilder.bild
					obj.bilder.bild = [
						preferred: true
					]

				if obj.bilder.bild[0]["eas:url"]
					@_migration.loginfo("Overwrite URL for '"+obj.bilder.unique_identifier+"': "+obj.bilder.bild[0]["eas:url"]+" -> "+ bild_fn)
				else
					@_migration.loginfo("Setting URL for '"+obj.bilder.unique_identifier+"': "+bild_fn)

				obj.bilder.bild[0]["eas:url"] = bild_fn
				obj.bilder.bild[0]["_post_process_source"] = obj.unique_identifier

			console.debug "csv:", csv, @_migration.getSettings(), filename_by_bildcode
			dfr.resolve()

		.fail =>
			CUI.problem(markdown: true, text: "Die Datei **"+fn+"** wurde nicht gefunden.")
			dfr.reject("File: "+fn+" for post process could not be read.")

		dfr.promise()


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