
import at.clockwork.time.timeType.domain.TimeTimeTypeDataTotal

import groovy.sql.Sql
import java.sql.Connection
import java.sql.DriverManager
import javax.sql.DataSource




class UpdateScriptService {

	def run(def connection, def dataSourceFields) {

		def last_person_id
		def last_time_time_type_id
		def last_value

//		int minId = 0
//		int maxId = 0
//		def row = connection.firstRow("select min(id) as min, max(id) as max from cw_time_time_type_data")
//		minId = row.min
//		maxId = row.max
//		if (!minId)
//			minId = 0
//		if (!maxId)
//			maxId = 0

//		int count = maxId
//		int offset = minId

		int offset = 0
		int count = at.clockwork.system.service.DataSourceService.getRecordCountOfDatabaseTable(connection, "cw_time_time_type_data")
		int maxRows = 100000

println "count=" + count

		long id
		long person_id
		long time_time_type_id
		Date date
		double limitv

count = 0

		for (offset=0; offset<count; offset+=maxRows) {

			String selectStatement =
				"select id, person_id, time_time_type_id, date, limitv " +
				"from cw_time_time_type_data " +
				"order by person_id, time_time_type_id, date"

println "-->offset=" + offset + " von=" + count
			connection.eachRow(selectStatement, offset, maxRows) {

				id = it.id
				person_id = it.person_id
				time_time_type_id = it.time_time_type_id
				date = it.date
				limitv = it.limitv

				if (!last_person_id || !last_time_time_type_id || last_value ||
					last_person_id != person_id || last_time_time_type_id != time_time_type_id || last_value != limitv) {

					def resultMap = at.clockwork.system.service.DataSourceService.execute(
						connection,
						dataSourceFields,
						[
							mySQLStatement:"insert into cw_time_time_type_data_limit (version, person_id, date, time_time_type_id, limit_value) select 0, person_id, date, time_time_type_id, limitv from cw_time_time_type_data where id = " + id,
							msSQLStatement:"insert into cw_time_time_type_data_limit (version, person_id, date, time_time_type_id, limit_value) select 0, person_id, date, time_time_type_id, limitv from cw_time_time_type_data where id = " + id
						]
					)

					last_person_id = person_id
					last_time_time_type_id = time_time_type_id
					last_value = limitv

				}

			}

		}


		true
	}
}