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

import at.clockwork.security.domain.*

import at.clockwork.transfer.gwtTransfer.client.enumeration.*

import at.clockwork.utility.ToolsService

import at.clockwork.singleton.SystemConfigurations
import at.clockwork.singleton.GrailsApplicationHolder

import grails.util.Holders

class TimeTimeModelService {

	static transactional = false

	def securityService = Holders.grailsApplication.mainContext.getBean 'securityService'

	def timeModel2DetailWriteService = Holders.grailsApplication.mainContext.getBean 'timeModel2DetailWriteService'

	def systemConfigurations = SystemConfigurations.getInstance()
	def grailsApplicationHolder = GrailsApplicationHolder.getInstance()

	final static int LOG_INFO = 1
	final static int LOG_DEBUG = 2
	int logLevel = LOG_DEBUG

	def run() {
		
		log "Tagesmodelle EVERY_DAY - Start"
	
		try {

			def grailsApplication = grailsApplicationHolder.getGrailsApplication()

			for (domainClass in grailsApplication.domainClasses.findAll { it.clazz.simpleName.startsWith("TimeModel2") }) {

				Class clazz = domainClass.clazz
				for (def domainObject in  clazz.findAllWhere( deleted : false, dayEnum : TimeModelDayEnum.NORMAL )) {
					println "  $domainObject / ${domainObject.getClass()}: ${domainObject.properties}"

					Map findMap = [:]
					domainObject.properties.each { prop ->

//						println "  $prop / ${prop?.getClass()}"
						for ( propMap in prop ) {
//							println "   key=${prop.key} value=${prop.value}"

							switch( propMap.key ) {

								case "id":
								case "version":
								case "dateCreated":
								case "lastUpdated":
								case "updateCounter":
								case "dayEnum":
									break

								default:
									def fieldProps = domainClass.properties.find { it.getName() == propMap.key }
									if ( fieldProps?.persistent == true ) {
										findMap[ propMap.key ] = propMap.value
									}
									break

							}

						}
					}

					List list = clazz.findAllWhere( findMap )
					if ( list.size() == 3 && 
						list.any { it.dayEnum == TimeModelDayEnum.NORMAL } &&
						list.any { it.dayEnum == TimeModelDayEnum.HOLIDAY_1 } &&
						list.any { it.dayEnum == TimeModelDayEnum.HOLIDAY_2 }
					) {
						list[0].dayEnum = TimeModelDayEnum.EVERY_DAY
						timeModel2DetailWriteService.save( list[0] )

						list[1].deleted = true
						timeModel2DetailWriteService.save( list[1] )

						list[2].deleted = true
						timeModel2DetailWriteService.save( list[2] )
						
					}


				}

			}


		} catch(e) {
			println e.getMessage()
			println e.getStackTrace()
		}
		
		log "Tagesmodelle EVERY_DAY - Ende"

	}

	void log(String text, level = LOG_INFO) {

		switch(logLevel) {
			case LOG_DEBUG:
				println text
			break

			case LOG_INFO:
			default:
				if (level == LOG_INFO)
					println text
			break
		}

	}

}
