import org.codehaus.groovy.grails.plugins.springsecurity.Secured
import org.codehaus.groovy.grails.commons.ConfigurationHolder
import com.zeddware.grails.plugins.filterpane.FilterUtils

@Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager'])
class TaskDetailedController extends BaseController {

    def authService
    def taskService
    def taskSearchService
    def filterService
    def exportService
    def dateUtilService

    // these actions only accept POST requests
    static allowedMethods = [save:'POST', update:'POST', restore:'POST', trash:'POST', approve:'POST', renegeApproval:'POST', complete:'POST', reopen:'POST']

    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
    def index = { redirect(action: 'search', params: params) }

    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
    def list = {
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100 )
        [ taskInstanceList: Task.list( params ), taskInstanceTotal: Task.count() ]
    }

    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
    def setTaskSearchParamsMax = {
        def max = 1000
        if(params.newMax.isInteger()) {
            def i = params.newMax.toInteger()
            if(i > 0 && i <= max)
                session.taskSearchParamsMax = params.newMax
            if(i > max)
                session.taskSearchParamsMax = max
        }
        forward(action: 'search', params: params)
    }

    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
    def search = {

        if(session.taskSearchParamsMax)
            params.max = session.taskSearchParamsMax

        // TaskSearchService protects itself but filterPane does not.
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  1000 )

        def taskInstanceList = []
        def taskInstanceTotal
        def filterParams = [:]
        def personInstance = authService.currentUser

        // Quick Search:
        if(!FilterUtils.isFilterApplied(params)) {

            if(params.quickSearch == "searchMyTodays") {
                taskInstanceList = taskSearchService.getMyTodays(params)
                if(taskInstanceList.totalCount > 0) { params.message = "Today's tasks for ${personInstance.firstName} ${personInstance.lastName}." }
                else { params.message = "No tasks found for today." }
            }
            else if(params.quickSearch == "searchInTheLastWeek") {
                taskInstanceList = taskSearchService.getInTheLastWeek(params)
                if(taskInstanceList.totalCount > 0) { params.message = "Tasks with Target Start Date in the last week." }
                else { params.message = "No tasks found for the last week." }
            }
            else if(params.quickSearch == "searchMyInTheLastWeek") {
                taskInstanceList = taskSearchService.getMyInTheLastWeek(params)
                if(taskInstanceList.totalCount > 0) { params.message = "Tasks with Target Start Date in the last week for ${personInstance.firstName} ${personInstance.lastName}." }
                else { params.message = "No tasks found for the last week." }
            }
            else {
                //Default:
                taskInstanceList = taskSearchService.getTodays(params)
                if(taskInstanceList.totalCount > 0) { params.message = "Today's tasks." }
                else { params.message = "No tasks found for today." }
                params.quickSearch = "searchTodays"
            }

            taskInstanceTotal = taskInstanceList.totalCount
            filterParams.quickSearch = params.quickSearch
        }
        else {
            // filterPane:
            taskInstanceList = filterService.filter( params, Task )
            taskInstanceTotal = filterService.count( params, Task )
            filterParams = com.zeddware.grails.plugins.filterpane.FilterUtils.extractFilterParams(params)
        }

        // export plugin:
        if(params?.format && params.format != "html") {

            def dateFmt = { date ->
                formatDate(format: "EEE, dd-MMM-yyyy", date: date)
            }

            String title
            if(params.quickSearch)
                title = "${params.quickSearch} tasks."
            else
                title = "Filtered tasks."

            response.contentType = ConfigurationHolder.config.grails.mime.types[params.format]
            response.setHeader("Content-disposition", "attachment; filename=tasks.${params.extension}")
            List fields = ["id", "targetStartDate", "description", "leadPerson", "taskPriority", "taskStatus"]
            Map labels = ["id": "ID", "targetStartDate": "Target Start Date", "description": "Description",
                                    "leadPerson": "Lead Person", "taskPriority": "Task Priority", "taskStatus": "Task Status"]
            Map formatters = [ targetStartDate: dateFmt]
            Map parameters = [title: title, separator: ","]

            exportService.export(params.format, response.outputStream, taskInstanceList, fields, labels, formatters, parameters)
        }

        // Add some basic params to filterParams.
        filterParams.max = params.max
        filterParams.offset = params.offset?.toInteger() ?: 0
        filterParams.sort = params.sort ?: "id"
        filterParams.order = params.order ?: "desc"

        return[ taskInstanceList: taskInstanceList,
                taskInstanceTotal: taskInstanceTotal,
                filterParams: filterParams ]

    } // end search()

    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
    def searchCalendar = {
        params.max = 30

        // Quick Search:
        if(!FilterUtils.isFilterApplied(params)) {
            def taskInstanceList = []
            def personInstance = authService.currentUser

            if(params.quickSearch == "searchMyTodays") {
                taskInstanceList = taskSearchService.getMyTodays(params)
                if(taskInstanceList.totalCount > 0) { params.message = "Today's tasks for ${personInstance.firstName} ${personInstance.lastName}." }
                else { params.message = "No tasks found for today." }
                if(taskInstanceList.totalCount > params.max) { params.message = "Too many results, only the first ${params.max} shown" }
            }
            else if(params.quickSearch == "searchInTheLastWeek") {
                taskInstanceList = taskSearchService.getInTheLastWeek(params)
                if(taskInstanceList.totalCount > 0) { params.message = "Tasks with Target Start Date in the last week." }
                else { params.message = "No tasks found for the last week." }
                if(taskInstanceList.totalCount > params.max) { params.message = "Too many results, only the first ${params.max} shown" }
            }
            else if(params.quickSearch == "searchMyInTheLastWeek") {
                taskInstanceList = taskSearchService.getMyInTheLastWeek(params)
                if(taskInstanceList.totalCount > 0) { params.message = "Tasks with Target Start Date in the last week for ${personInstance.firstName} ${personInstance.lastName}." }
                else { params.message = "No tasks found for the last week." }
                if(taskInstanceList.totalCount > params.max) { params.message = "Too many results, only the first ${params.max} shown" }
            }
            else {
                //Default:
                taskInstanceList = taskSearchService.getTodays(params)
                if(taskInstanceList.totalCount > 0) { params.message = "Today's tasks." }
                else { params.message = "No tasks found for today." }
                if(taskInstanceList.totalCount > params.max) { params.message = "Too many results, only the first ${params.max} shown" }
                params.quickSearch = "searchTodays"
            }
            return[taskInstanceList: taskInstanceList, taskInstanceTotal: taskInstanceList.totalCount, filterParams: params]
        }
        // filterPane:
        def taskInstanceTotal = filterService.count( params, Task )
        if(taskInstanceTotal > params.max) { params.message = "Too many results, only the first ${params.max} shown" }
        return[ taskInstanceList: filterService.filter( params, Task ),
            taskInstanceTotal: taskInstanceTotal,
            filterParams: com.zeddware.grails.plugins.filterpane.FilterUtils.extractFilterParams(params),
            params:params ]
    }

    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
    def budget = {
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100 )

        // Quick Search:
        if(!FilterUtils.isFilterApplied(params)) {
            def taskInstanceList = []
            def personInstance = authService.currentUser

            if(params.quickSearch == "budgetUnplanned") {
                taskInstanceList = taskSearchService.getBudgetUnplanned(params)
                if(taskInstanceList.totalCount > 0) { params.message = "Budget unplanned tasks in the last week." }
                else { params.message = "No tasks found." }
            }
            //else if(params.quickSearch == "budgetPlanned") {
            else {
                //Default:
                taskInstanceList = taskSearchService.getBudgetPlanned(params)
                if(taskInstanceList.totalCount > 0) { params.message = "Budget planned Tasks in the last week." }
                else { params.message = "No tasks found.." }
            }
            // export plugin:
            if(params?.format && params.format != "html") {

                def dateFmt = { date ->
                    formatDate(format: "EEE, dd-MMM-yyyy", date: date)
                }
                response.contentType = ConfigurationHolder.config.grails.mime.types[params.format]
                response.setHeader("Content-disposition", "attachment; filename=tasks.${params.extension}")
                List fields = ["id", "targetStartDate", "description", "leadPerson", "taskStatus", "taskType"]
                Map labels = ["id": "ID", "targetStartDate": "Target Start Date", "description": "Description",
                                        "leadPerson": "Lead Person", "taskStatus": "Task Status", "taskType": "Task Type"]
                Map formatters = [ targetStartDate: dateFmt]
                String title = "${params.quickSearch} tasks in the last week."
                Map parameters = [title: title, separator: ","]

                exportService.export(params.format, response.outputStream, taskInstanceList, fields, labels, formatters, parameters) 
            }
            return[taskInstanceList: taskInstanceList, taskInstanceTotal: taskInstanceList.totalCount, filterParams: params]
        }
        // filterPane:
        return[ taskInstanceList: filterService.filter( params, Task ),
            taskInstanceTotal: filterService.count( params, Task ),
            filterParams: com.zeddware.grails.plugins.filterpane.FilterUtils.extractFilterParams(params),
            params:params ]
    }

    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
    def show = {

        // In the case of an actionSubmit button, rewrite action name from 'index'.
        if(params._action_Show)
        { params.action='show' }

        def showTab = [:]
        switch (params.showTab) {
            case "showProcedureTab":
                showTab.procedure =  new String("true")
                break
            case "showRecurrenceTab":
                showTab.recurrence =  new String("true")
                break
            case "showInventoryTab":
                showTab.inventory = new String("true")
                break
            case "showSubTasksTab":
                showTab.subTasks = new String("true")
                break
            default:
                showTab.task = new String("true")
        }

        def taskInstance = Task.get( params.id )

        if(!taskInstance) {
            flash.message = "Task not found with id ${params.id}"
            redirect(action: 'search')
        }
        else {
            params.max = 10
            params.order = "desc"
            params.sort = "id"

            def entryWorkDoneList = Entry.withCriteria {
                                                                eq("entryType", EntryType.get(2))
                                                                eq("task", taskInstance)
                                                        }

            def entryFaultList = Entry.withCriteria {
                                                                eq("entryType", EntryType.get(1))
                                                                eq("task", taskInstance)
                                                        }

            def subTaskInstanceList = Task.findAllByParentTaskAndTrash(taskInstance, false, params)
            def subTaskInstanceTotal = Task.countByParentTaskAndTrash(taskInstance, false)

            def inventoryMovementList = InventoryMovement.findAllByTask(taskInstance, [max:100, sort:"id", order:"desc", offset:0])

            def taskModificationList = TaskModification.findAllByTask(taskInstance, [max:100, sort:"id", order:"asc", offset:0])

            def assignedGroupList = taskInstance.assignedGroups.sort { p1, p2 -> p1.personGroup.name.compareToIgnoreCase(p2.personGroup.name) }
            def assignedPersonList = taskInstance.assignedPersons.sort { p1, p2 -> p1.person.firstName.compareToIgnoreCase(p2.person.firstName) }

            def taskProcedureInstance = TaskProcedure.get(taskInstance.taskProcedure?.id)
            def taskProcedureExits = new Boolean("true")
            if(!taskProcedureInstance) {
                taskProcedureExits = false
            }

            params.order = "asc"
            params.sort = "procedureStepNumber"
            def maintenanceActionList = MaintenanceAction.findAllByTaskProcedure(taskProcedureInstance, params)

            def taskRecurringScheduleInstance = TaskRecurringSchedule.get(taskInstance.taskRecurringSchedule?.id)
            def taskRecurringScheduleExits= new Boolean("true")
            if(!taskRecurringScheduleInstance) {
                taskRecurringScheduleExits = false
            }

            return [ taskInstance: taskInstance,
                            entryWorkDoneList: entryWorkDoneList,
                            entryFaultList: entryFaultList,
                            taskProcedureInstance: taskProcedureInstance,
                            taskProcedureExits: taskProcedureExits,
                            showTab: showTab,
                            subTaskInstanceList: subTaskInstanceList,
                            subTaskInstanceTotal: subTaskInstanceTotal,
                            subTaskInstanceMax: params.max,
                            maintenanceActionList: maintenanceActionList,
                            taskRecurringScheduleInstance: taskRecurringScheduleInstance,
                            taskRecurringScheduleExits: taskRecurringScheduleExits,
                            inventoryMovementList: inventoryMovementList,
                            taskModificationList: taskModificationList,
                            assignedGroupList: assignedGroupList,
                            assignedPersonList: assignedPersonList]
        }
    }

    def restore = {

        if(!Task.exists(params.id)) {
            flash.message = "Task not found with id ${params.id}"
            redirect(action: 'search')
        }

        def result = taskService.restore(params)

        if(!result.error) {
                flash.message = "Task ${params.id} has been restored."
                redirect(action: 'show', id: result.taskInstance.id)
        }
        else {
            if(result.taskInstance) {
                render(view:'edit',model:[taskInstance:result.taskInstance])
            }
            else {
                flash.message = "Task could not be updated."
                redirect(action: 'search')
            }
        }

    }

    def trash = {

        if(!Task.exists(params.id)) {
            flash.message = "Task not found with id ${params.id}."
            redirect(action: 'search')
        }

        def result = taskService.trash(params)

        if(!result.error) {
                flash.message = "Task ${params.id} has been moved to trash."
                redirect(action: 'search')
        }
        else {
            if(result.taskInstance) {
                render(view:'edit',model:[taskInstance:result.taskInstance])
            }
            else {
                flash.message = "Task could not be updated."
                redirect(action: 'search')
            }
        }

    }

    def approve = {

        if(!Task.exists(params.id)) {
            flash.message = "Task not found with id ${params.id}."
            redirect(action: 'search')
        }

        def result = taskService.approve(params)

        if(!result.error) {
                flash.message = "Task ${params.id} has been approved."
                redirect(action: 'show', id: result.taskInstance.id)
        }
        else {
            if(result.taskInstance) {
                render(view:'edit',model:[taskInstance:result.taskInstance])
            }
            else {
                flash.message = "Task could not be updated."
                redirect(action: 'search')
            }
        }

    }

    def renegeApproval = {

        if(!Task.exists(params.id)) {
            flash.message = "Task not found with id ${params.id}."
            redirect(action: 'search')
        }

        def result = taskService.renegeApproval(params)

        if(!result.error) {
                flash.message = "Task ${params.id} has had approval removed."
                redirect(action: 'show', id: result.taskInstance.id)
        }
        else {
            if(result.taskInstance) {
                render(view:'edit',model:[taskInstance:result.taskInstance])
            }
            else {
                flash.message = "Task could not be updated."
                redirect(action: 'search')
            }
        }

    }

    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
    def complete = {

        if(!Task.exists(params.id)) {
            flash.message = "Task not found with id ${params.id}."
            redirect(action: 'search')
        }

        def result = taskService.complete(params)

        if(!result.error) {
                flash.message = "Task ${params.id} has been completed."
                redirect(action: 'show', id: result.taskInstance.id)
        }
        else {
            if(result.taskInstance) {
                render(view:'edit',model:[taskInstance:result.taskInstance])
            }
            else {
                flash.message = "Task could not be updated."
                redirect(action: 'search')
            }
        }

    }

    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
    def reopen = {

        if(!Task.exists(params.id)) {
            flash.message = "Task not found with id ${params.id}."
            redirect(action: 'search')
        }

        def result = taskService.reopen(params)

        if(!result.error) {
                flash.message = "Task ${params.id} has been reopened."
                redirect(action: 'show', id: result.taskInstance.id)
        }
        else {
            if(result.taskInstance) {
                render(view:'edit',model:[taskInstance:result.taskInstance])
            }
            else {
                flash.message = "Task could not be updated."
                redirect(action: 'search')
            }
        }

    }

    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
    def edit = {

        // In the case of an actionSubmit button, rewrite action name from 'index'.
        if(params._action_Edit)
        { params.action='edit' }

        def taskInstance = Task.get( params.id )

        if(!taskInstance) {
            flash.message = "Task not found with id ${params.id}"
            redirect(action: 'search')
        }
        else {
            if(taskInstance.trash) {
                flash.message = "You may not edit tasks that are in the trash."
                redirect(action: 'show', id: taskInstance.id)
                return
            }
//             def possibleParentList = taskService.possibleParentList(taskInstance)
//             return [ taskInstance : taskInstance, possibleParentList: possibleParentList ]
            return [ taskInstance : taskInstance ]
        }
    }

    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
    def update = {

        if(!Task.exists(params.id)) {
            flash.message = "Task not found with id ${params.id}"
            redirect(action: 'search')
        }

        def result = taskService.update(params)

        if(!result.error) {
                flash.message = "Task ${params.id} updated"
                redirect(action: 'show', id: result.taskInstance.id)
        }
        else {
            render(view:'edit',model:[taskInstance:result.taskInstance.attach()])
        }

    }

    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
    def create = {
        def taskInstance = new Task()

        // Set the targetStartDate if specified, used by searchCalendar view.
        if(params.year && params.month && params.day)
            taskInstance.targetStartDate = dateUtilService.makeDate(params.year, params.month, params.day)

        // Default leadPerson to current user, unless supplied in params.
        taskInstance.leadPerson = authService.currentUser
        taskInstance.properties = params
        return ['taskInstance': taskInstance]
    }

    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
    def save = {
        def result = taskService.create(params)

        if(!result.error) {
            flash.message = "Task ${result.taskInstance.id} created."
            redirect(action: 'show', id: result.taskInstance.id)
        }
        else {
            if(result.taskInstance) {
                render(view:'create', model:[taskInstance:result.taskInstance])
            }
            else {
                flash.message = "Could not create task."
                redirect(action: 'search')
            }

        }
    }

    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
    def listSubTasks = {
        def parentTaskInstance = Task.get(params.id)

        if(!parentTaskInstance) {
            flash.message = "Task not found with id ${params.id}"
            redirect(action: 'search')
        }
        else {
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
        def subTaskInstanceList = Task.findAllByParentTaskAndTrash(parentTaskInstance, false, params)
        def subTaskInstanceTotal = Task.countByParentTaskAndTrash(parentTaskInstance, false)

        [ taskInstanceList: subTaskInstanceList,
            taskInstanceTotal:  subTaskInstanceTotal,
            parentTaskInstance: parentTaskInstance]
        }
    }

    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
    def createSubTask = {
        def parentTaskInstance = Task.get(params.id)

        if(parentTaskInstance) {

            def result = taskService.createSubTask(parentTaskInstance)
            if(!result.error) {
                flash.message = "Sub Task ${result.taskInstance.id} created, please edit and update to your requirements."
                redirect(action: 'edit', id: result.taskInstance.id)
            }
            else {
                if(result.taskInstance.errors.hasFieldErrors("parentTask")) {
                    flash.message = g.message(code:"task.operationNotPermittedOnTaskInTrash")
                    redirect(action: 'show', id:  parentTaskInstance.id)
                }
                else {
                    render(view: 'create', model:[taskInstance: result.taskInstance])
                }
            }
        }

        else {
            flash.message = "Task not found with id ${params.id}"
            redirect(action: 'search')
        }
    }

} // end of class.
