
import at.dockwork.common.domain.*
import at.dockwork.common.person.domain.*




class UpdateScriptService {

	def run(def connection, def dataSourceFields) {

		if (at.dockwork.system.service.DataSourceService.getRecordCountOfDatabaseTable(connection, 'dw_identification_2_identification_code') == 0 &&
			at.dockwork.system.service.DataSourceService.getRecordCountOfDatabaseTable(connection, 'dw_person_2_identification') == 0 &&
			at.dockwork.system.service.DataSourceService.existsFieldInDatabaseTable(connection, 'dw_identification_code', 'identification_id') &&
			at.dockwork.system.service.DataSourceService.existsFieldInDatabaseTable(connection, 'dw_identification', 'person_id')
			) {

			at.dockwork.system.service.DataSourceService.execute(
				connection,
				dataSourceFields,
				[
					mySQLStatement:"insert into dw_person_2_identification (version, person_id, identification_id) select 0, person_id, id from dw_identification where person_id is not null",
					msSQLStatement:"insert into dw_person_2_identification (version, person_id, identification_id) select 0, person_id, id from dw_identification where person_id is not null"
				]
			)

			at.dockwork.system.service.DataSourceService.execute(
				connection,
				dataSourceFields,
				[
					mySQLStatement:"insert into dw_identification_2_identification_code (version, identification_id, identification_code_id) select 0, identification_id, id from dw_identification_code where identification_id is not null",
					msSQLStatement:"insert into dw_identification_2_identification_code (version, identification_id, identification_code_id) select 0, identification_id, id from dw_identification_code where identification_id is not null"
				]
			)

			at.dockwork.system.service.DataSourceService.execute(
				connection,
				dataSourceFields,
				[
					mySQLStatement:"update dw_identification_code set identification_id = null",
					msSQLStatement:"update dw_identification_code set identification_id = null"
				]
			)

			at.dockwork.system.service.DataSourceService.execute(
				connection,
				dataSourceFields,
				[
					mySQLStatement:"update dw_identification set person_id = null",
					msSQLStatement:"update dw_identification set person_id = null"
				]
			)

			at.dockwork.system.service.DataSourceService.execute(
				connection,
				dataSourceFields,
				[
					mySQLStatement:"alter table dw_identification drop column valid_from",
					msSQLStatement:"alter table dw_identification drop column valid_from"
				]
			)

			at.dockwork.system.service.DataSourceService.execute(
				connection,
				dataSourceFields,
				[
					mySQLStatement:"alter table dw_identification drop column valid_to",
					msSQLStatement:"alter table dw_identification drop column valid_to"
				]
			)
		}

		true
	}
}
