import at.dockwork.common.domain.*
import at.dockwork.generated.service.*

import grails.util.Holders

class UpdateScriptService {

	TriggerWriteService triggerWriteService = Holders.grailsApplication.mainContext.getBean 'triggerWriteService'

	def run(def connection, def dataSourceFields) {

        def gormCriteria = Identification.createCriteria()
        def list = gormCriteria {
            and {
                like("number", "PIN_%")
                eq("deleted", false)
            }
        }

        list = list.sort{ it.id }.sort{ it.number }.reverse()
        list.each { identification ->

            def parts = identification.number.split("_")

            if (parts.size() == 2) {

                Person person = Person.findWhere(number:parts[1], deleted:false)
                if (person) {
                    String newNumber = "PIN_PID=" + person.id
                    if (Identification.findWhere(number:newNumber, deleted:false)) {
                        identification.deleted = true
                    } else {
                        identification.number = newNumber
                    }
                } else {
                    identification.deleted = true
                }

            }
            triggerWriteService.save(identification)
        }

		true
	}
}