import grails.orm.PagedResultList

/**
* Service class that encapsulates the business logic for Task searches.
*/
class TaskReportService {

    boolean transactional = false

    def authService
    def dateUtilService
//     def messageSource

//     def g = new org.codehaus.groovy.grails.plugins.web.taglib.ApplicationTagLib()

    def paramsMax = 100000

    /**
    * Selects and returns the reactive ratio.
    * @param params The request params, may contain param to specify the search.
    * @param locale The locale to use when generating result.message.
    */
    def getReactiveRatio(params, locale) {
        def result = [:]

        def namedParams = [:]
        namedParams.startDate = params.startDate ?: dateUtilService.today
        namedParams.endDate = params.endDate ?: dateUtilService.today
        namedParams.endDate++ // Start of next day required.
        namedParams.immediateCallout = TaskType.read(1)
        namedParams.unscheduledBreakin = TaskType.read(2)
        namedParams.preventativeMaintenance = TaskType.read(4)
        namedParams.notStarted = TaskStatus.read(1)

        result.taskQuery = "from Task as task \
                                        where (task.trash = false \
                                                    and task.taskStatus != :notStarted \
                                                    and task.targetStartDate < :endDate \
                                                    and task.targetStartDate >= :startDate \
                                                    and ( \
                                                        task.taskType = :immediateCallout \
                                                        or task.taskType = :unscheduledBreakin \
                                                        or task.taskType = :preventativeMaintenance \
                                                    ) \
                                        )"

        result.taskQuery = "select distinct task " + result.taskQuery
        result.taskList = Task.executeQuery(result.taskQuery, namedParams)
        result.taskCount = result.taskList.size()

        // Counts
        result.totalAssetsOnTasksCount = 0
        result.immediateCalloutCount = 0
        result.unscheduledBreakinCount = 0
        result.preventativeMaintenanceCount = 0

        result.summaryOfCalculationMethod = 'HQL query: \n\n'
        def tempStringArray = result.taskQuery.split('    ')
        tempStringArray.each() {
            if(it != '') result.summaryOfCalculationMethod += it +'\n'
        }
        result.summaryOfCalculationMethod += '\n'+'Calculations: '+'\n\n'

        result.summaryOfCalculationMethod += 'totalAssetsOnTasksCount = A count of unique assets on each task. \n'
        result.taskList.each() { task ->
            if(task.primaryAsset) {
                result.totalAssetsOnTasksCount++
                if(task.taskType == namedParams.immediateCallout) result.immediateCalloutCount++
                if(task.taskType == namedParams.unscheduledBreakin) result.unscheduledBreakinCount++
                if(task.taskType == namedParams.preventativeMaintenance) result.preventativeMaintenanceCount++
            }
            task.associatedAssets.each() { associatedAsset ->
                if(associatedAsset.id != task.primaryAsset?.id) {
                    result.totalAssetsOnTasksCount++
                    if(task.taskType == namedParams.immediateCallout) result.immediateCalloutCount++
                    if(task.taskType == namedParams.unscheduledBreakin) result.unscheduledBreakinCount++
                    if(task.taskType == namedParams.preventativeMaintenance) result.preventativeMaintenanceCount++
                }
            }
        } // each() task

        // Percentages
        result.immediateCalloutPercentage = 0
        result.totalPreventativePercentage = 0

        result.summaryOfCalculationMethod += 'totalPreventativeCount = unscheduledBreakinCount + preventativeMaintenanceCount\n'
        result.totalPreventativeCount = result.unscheduledBreakinCount + result.preventativeMaintenanceCount
        try {
            result.summaryOfCalculationMethod += 'immediateCalloutPercentage = (immediateCalloutCount / totalAssetsOnTasksCount)*100 \n'
            result.summaryOfCalculationMethod += 'totalPreventativePercentage = (totalPreventativeCount / totalAssetsOnTasksCount)*100 \n'
            result.immediateCalloutPercentage = (result.immediateCalloutCount / result.totalAssetsOnTasksCount)*100
            result.totalPreventativePercentage = (result.totalPreventativeCount / result.totalAssetsOnTasksCount)*100
        }
        catch(ArithmeticException e) {
            log.error "Could not calculate percentages: "+e
        }

        // Success.
        return result

    } // getQuickSearch


} // end class
