import at.clockwork.common.domain.*

class UpdateScriptService {

	def run(def connection, def dataSourceFields) {

        List fields = [
             "code"
            ,"code2"
            ,"code3"
            ,"code4"
            ,"code5"
        ]
	    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 Script where $field like '%${mapItem.search}%'"
                Script.executeQuery(selectStatement).each {
                    Script script = Script.get(it[0])
                    if (script) {
                        String text = it[1]
                        text = text.replace(mapItem.search, mapItem.replace)
                        String updateStatement = "update Script set $field=:text where id=:id"
                        Script.executeUpdate(updateStatement, [id:it[0], text:text])
                        script.save(flush:true)
                    }
                }

            }
        }

		true
	}
}