import org.codehaus.groovy.grails.plugins.springsecurity.Secured
import org.codehaus.groovy.runtime.TimeCategory
import java.text.SimpleDateFormat

class TaskRecurringScheduleDetailedController extends BaseController {

    def dateUtilService

    def index = { redirect(action:list,params:params) }

    // the delete, save and update actions only accept POST requests
    static allowedMethods = [delete:'POST', save:'POST', update:'POST']

    def list = {
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
        [ taskRecurringScheduleInstanceList: TaskRecurringSchedule.list( params ), taskRecurringScheduleInstanceTotal: TaskRecurringSchedule.count() ]
    }

    def show = {
        def taskRecurringScheduleInstance = TaskRecurringSchedule.get( params.id )

        if(!taskRecurringScheduleInstance) {
            flash.message = "Recurring Schedule not found with id ${params.id}"
            redirect(action:list)
        }
        else { return [ taskRecurringScheduleInstance : taskRecurringScheduleInstance ] }
    }

    def delete = {
        def taskRecurringScheduleInstance = TaskRecurringSchedule.get( params.id )
        if(taskRecurringScheduleInstance) {
            try {
                taskRecurringScheduleInstance.delete(flush: true)
                flash.message = "Recurring Schedule ${params.id} deleted"
                redirect(action:list)
            }
            catch(org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "Recurring Schedule ${params.id} could not be deleted"
                redirect(action:show,id:params.id)
            }
        }
        else {
            flash.message = "Recurring Schedule not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def edit = {
        def taskRecurringScheduleInstance = TaskRecurringSchedule.get( params.id )

        if(!taskRecurringScheduleInstance) {
            flash.message = "Recurring Schedule not found with id ${params.id}"
            redirect(action:list)
        }
        else {
            return [ taskRecurringScheduleInstance : taskRecurringScheduleInstance]
        }
    }

    def update = {
        TaskRecurringSchedule.withTransaction { status ->

            def taskRecurringScheduleInstance = TaskRecurringSchedule.get( params.id )
            if(taskRecurringScheduleInstance) {

                if(params.version) {
                    def version = params.version.toLong()
                    if(taskRecurringScheduleInstance.version > version) {
                        taskRecurringScheduleInstance.errors.rejectValue("version", "taskRecurringSchedule.optimistic.locking.failure", "Another user has updated this Recurring Schedule while you were editing.")
                        render(view:'edit',model:[taskRecurringScheduleInstance:taskRecurringScheduleInstance])
                        return
                    }
                }

                Date originalDate = taskRecurringScheduleInstance.nextTargetStartDate
                taskRecurringScheduleInstance.properties = params  // Domain object is now 'dirty'.
                Date newDate = taskRecurringScheduleInstance.nextTargetStartDate

                // If user changes nextTargetStartDate then ensure it is in the future, otherwise it's ok to keep the original date.
                if(originalDate.getTime() != newDate.getTime())
                {
                    if(newDate < dateUtilService.getToday()) 
                    {
                        status.setRollbackOnly()  // Only allow the transaction to Rollback, preventing flush due to 'dirty'.
                        taskRecurringScheduleInstance.errors.rejectValue("nextTargetStartDate", "taskRecurring.nextTargetStartDate.NotInTheFuture")
                        render(view:'edit',model:[taskRecurringScheduleInstance:taskRecurringScheduleInstance])
                        return
                    }
                }

                taskRecurringScheduleInstance.setNextGenerationDate()
                taskRecurringScheduleInstance.setNextTargetCompletionDate()

                if(!taskRecurringScheduleInstance.hasErrors() && taskRecurringScheduleInstance.save(flush: true))
                {
                    flash.message = "Recurring Schedule ${params.id} updated"
                    redirect(action:show,id:taskRecurringScheduleInstance.id)
                }
                else 
                {
                    render(view:'edit',model:[taskRecurringScheduleInstance:taskRecurringScheduleInstance])
                }
            }
            else 
            {
                flash.message = "Recurring Schedule not found with id ${params.id}"
                redirect(action:edit,id:params.id)
            }

        } // end withTransaction
    } // end update()

    def create = {
        try {
            def taskInstance = Task.get(params.taskInstance.id)
            def taskRecurringScheduleInstance = new TaskRecurringSchedule()
            taskRecurringScheduleInstance.task = taskInstance
            return [taskRecurringScheduleInstance: taskRecurringScheduleInstance]
        }
        catch(Exception e) {
            flash.message = "Please select a task, then Create a Recurring Schedule for it"
            redirect(controller:"taskDetailed", action:"search")
        }
    } // end create()

    def save = {
        def taskRecurringScheduleInstance = new TaskRecurringSchedule(params)
        def taskInstance = Task.get(params.task.id)

        if(taskInstance.taskRecurringSchedule) {
            flash.message = "This task already has a recurring schedule"
            redirect(controller:"taskDetailed", action:"show", id: params.task.id)
        }
        else {

            if(taskRecurringScheduleInstance.nextTargetStartDate < dateUtilService.getToday()) {
                taskRecurringScheduleInstance.errors.rejectValue("nextTargetStartDate", "taskRecurring.nextTargetStartDate.NotInTheFuture")
            }

            if(!taskRecurringScheduleInstance.hasErrors() && taskRecurringScheduleInstance.save(flush: true)) {

                taskInstance.taskRecurringSchedule = taskRecurringScheduleInstance

                if(taskInstance.save(flush: true)) {
                    flash.message = "Recurring Schedule ${taskRecurringScheduleInstance.id} created"
                    redirect(action:show,id:taskRecurringScheduleInstance.id)
                }
                else {
                    flash.message = "Task could not be saved and therefore the Recurring Schedule has been disgarded, cause unknown."	
                    render(view:'create',model:[taskRecurringScheduleInstance:taskRecurringScheduleInstance])
                }
            }
            else {
                render(view:'create',model:[taskRecurringScheduleInstance:taskRecurringScheduleInstance])
            }
        }

    } // end save()

}
