import at.clockwork.time.timeModel.domain.*

class UpdateScriptService {

	def run(def connection, def dataSourceFields) {

        List fields = [
             "calculationProgram"
            ,"calculationProgram2"
            ,"calculationProgram3"
            ,"calculationProgram4"
            ,"calculationProgram5"
        ]
	    List list = [
	         [search:"getTimeModel2PlusTime(calculationData.timeTimeModel, calculationData.dayEnum)", replace:"getTimeModel2PlusTime(calculationData)"]
	        ,[search:"getTimeModel2PlusTime(_cd.timeTimeModel, _cd.dayEnum)", replace:"getTimeModel2PlusTime(calculationData)"]
	        ,[search:"getTimeModel2MinusTime(calculationData.timeTimeModel, calculationData.dayEnum)", replace:"getTimeModel2MinusTime(calculationData)"]
	        ,[search:"getTimeModel2MinusTime(_cd.timeTimeModel, _cd.dayEnum)", replace:"getTimeModel2MinusTime(calculationData)"]
	        ,[search:"getTimeModel2PauseTime(calculationData.timeTimeModel, calculationData.dayEnum)", replace:"getTimeModel2PauseTime(calculationData)"]
	        ,[search:"getTimeModel2PauseTime(_cd.timeTimeModel, _cd.dayEnum)", replace:"getTimeModel2PauseTime(calculationData)"]
	    ]

        for (String field in fields) {
            for (Map mapItem in list) {

                String selectStatement = "select id, $field from TimeTimeModel where $field like '%${mapItem.search}%'"
                TimeTimeModel.executeQuery(selectStatement).each {
                    TimeTimeModel timeTimeModel = TimeTimeModel.get(it[0])
                    if (timeTimeModel) {
                        String text = it[1]
                        text = text.replace(mapItem.search, mapItem.replace)
                        String updateStatement = "update TimeTimeModel set $field=:text where id=:id"
                        TimeTimeModel.executeUpdate(updateStatement, [id:it[0], text:text])
                        timeTimeModel.save(flush:true)
                    }
                }

            }
        }

		true
	}
}