import org.codehaus.groovy.grails.plugins.springsecurity.Secured
import org.codehaus.groovy.grails.commons.ConfigurationHolder
import org.springframework.web.servlet.support.RequestContextUtils as RCU

class ReportController extends BaseController {

    def authService
    def dateUtilService
    def taskReportService
    def assetReportService
    def inventoryReportService

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

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

    def templatePortrait = {

        params.startDate = new Date()
        params.endDate = new Date()

        params.reportTitle = "Template Report (Portrait)"
        params.logoUrl = grailsApplication.mainContext.getResource('images/logo.png').getURL()
        params.currentUser = authService.currentUser
        params.startDateString = g.formatDate(format: "EEE, dd-MMM-yyyy", date: params.startDate)
        params.endDateString = g.formatDate(format: "EEE, dd-MMM-yyyy", date: params.endDate)

        def dataModel = createTemplateData()

        // Jasper plugin controller expects data to be a Collection.
        chain(controller:'jasper', action:'index', model:[data: [dataModel]], params:params)

    } // templatePortrait

    def templateLandscape = {

        params.startDate = new Date()
        params.endDate = new Date()

        params.reportTitle = "Template Report (Landscape)"
        params.logoUrl = grailsApplication.mainContext.getResource('images/logo.png').getURL()
        params.currentUser = authService.currentUser
        params.startDateString = g.formatDate(format: "EEE, dd-MMM-yyyy", date: params.startDate)
        params.endDateString = g.formatDate(format: "EEE, dd-MMM-yyyy", date: params.endDate)

        def dataModel = createTemplateData()

        // Jasper plugin controller expects data to be a Collection.
        chain(controller:'jasper', action:'index', model:[data: [dataModel]], params:params)

    } // templateLandscape

    private createTemplateData() {

        def result = [:]
        result.summaryOfCalculationMethod = "Summary string of the calculations performed."
        result.dataList = []
        for(i in 1..5) {
            def dataDetails = [:]
            dataDetails.description = "Data description " + i.toString()
            result.dataList << dataDetails
        }

        // Success.
        return result

    } // createTemplateData

    def downloadTemplate = {

        // params.fileName is not used directly to negate any security issues..
        def fileName = (params.fileName == 'templateLandscape.jrxml') ? 'templateLandscape.jrxml' : 'templatePortrait.jrxml'
        def f = grailsApplication.mainContext.getResource("reports/${fileName}").getFile()
        if(f.isFile()) {
            response.contentType = ConfigurationHolder.config.grails.mime.types["text"]
            response.setHeader("Content-disposition", "attachment; filename=${fileName}")
            render f.text
        }
        else
            render(status:404, text: "File Not Found: ${f}")

    } // downLoadTemplate

    def reactiveRatio = {

        def result = taskReportService.getReactiveRatio(params, RCU.getLocale(request))

        params.reportTitle = "Reactive Ratio Report"
        params.logoUrl = grailsApplication.mainContext.getResource('images/logo.png').getURL()
        params.currentUser = authService.currentUser
        params.startDateString = result.startDateString
        params.endDateString = result.endDateString

        if(!result.error) {
            // Jasper plugin controller expects data to be a Collection.
            chain(controller:'jasper', action:'index', model:[data: [result]], params:params)
            return
        }

        flash.errorMessage = g.message(code: result.error.code, args: result.error.args)
        redirect(controller: 'appCore', action: 'start', params: [showTab:'showReportsTab'])

    } // reactiveRatio

    def immediateCallouts = {

        def result = taskReportService.getImmediateCallouts(params, RCU.getLocale(request))

        params.reportTitle = "Immediate Callouts"
        params.logoUrl = grailsApplication.mainContext.getResource('images/logo.png').getURL()
        params.currentUser = authService.currentUser
        params.startDateString = result.startDateString
        params.endDateString = result.endDateString

        if(!result.error) {
            // Jasper plugin controller expects data to be a Collection.
            chain(controller:'jasper', action:'index', model:[data: [result]], params:params)
            return
        }

        flash.errorMessage = g.message(code: result.error.code, args: result.error.args)
        redirect(controller: 'appCore', action: 'start', params: [showTab:'showReportsTab'])

    } // immediateCallouts

    def stockTakeOverview = {

        params.reportTitle = "Stock Take Overview"
        params.logoUrl = grailsApplication.mainContext.getResource('images/logo.png').getURL()
        params.currentUser = authService.currentUser

        def dataModel = inventoryReportService.getStockTakeOverview(params, RCU.getLocale(request))

        // Jasper plugin controller expects data to be a Collection.
        chain(controller:'jasper', action:'index', model:[data: [dataModel]], params:params)

    } // stockTakeOverview

    def stockTakeByLocation = {

        params.reportTitle = "Stock Take By Location"
        params.logoUrl = grailsApplication.mainContext.getResource('images/logo.png').getURL()
        params.currentUser = authService.currentUser

        def dataModel = inventoryReportService.getStockTakeByLocation(params, RCU.getLocale(request))

        // Jasper plugin controller expects data to be a Collection.
        chain(controller:'jasper', action:'index', model:[data: [dataModel]], params:params)

    } // stockTakeByLocation

    def assetDetail = {

        params.reportTitle = "Asset Detail"
        params.logoUrl = grailsApplication.mainContext.getResource('images/logo.png').getURL()
        params.currentUser = authService.currentUser
        if(params.section.id == 'all') {
            params.section = "All"
            params.site = "All"
        }
        else {
            params.section = Section.get(params.section.id.toLong())
            params.site = params.section.site
        }

        def dataModel = assetReportService.getAssetDetail(params, RCU.getLocale(request))

        // Jasper plugin controller expects data to be a Collection.
        chain(controller:'jasper', action:'index', model:[data: dataModel], params:params)

    } // assetDetail

    def assetRegister = {

        params.reportTitle = "Asset Register"
        params.logoUrl = grailsApplication.mainContext.getResource('images/logo.png').getURL()
        params.currentUser = authService.currentUser

        def dataModel = assetReportService.getAssetRegister(params, RCU.getLocale(request))

        // Jasper plugin controller expects data to be a Collection.
        chain(controller:'jasper', action:'index', model:[data: [dataModel]], params:params)

    } // assetRegister

    def equipmentRegisterOhsGsp = {
        render(view: 'equipmentRegisterOhs')
    }

    def equipmentRegisterOhs = {

        params.calculateRegulatoryTaskCompletion = true
        def result = assetReportService.getEquipmentRegister(params, RCU.getLocale(request))

        params.reportTitle = "Equipment Register OH&S"
        params.logoUrl = grailsApplication.mainContext.getResource('images/logo.png').getURL()
        params.currentUser = authService.currentUser
        params.startDateString = result.startDateString
        params.endDateString = result.endDateString

        if(!result.error) {
            // Jasper plugin controller expects data to be a Collection.
            chain(controller:'jasper', action:'index', model:[data: [result]], params:params)
            return
        }

        flash.errorMessage = g.message(code: result.error.code, args: result.error.args)
        redirect(action: 'equipmentRegisterOhsGsp')

//         render {
//             dataModel.dataList.each {
//                 p("$it")
//             }
//         }

    } // equipmentRegisterOhs

    def equipmentRegisterFinancial = {

        params.reportTitle = "Equipment Register Financial"
        params.logoUrl = grailsApplication.mainContext.getResource('images/logo.png').getURL()
        params.currentUser = authService.currentUser

        def dataModel = assetReportService.getEquipmentRegister(params, RCU.getLocale(request))

        // Jasper plugin controller expects data to be a Collection.
        chain(controller:'jasper', action:'index', model:[data: [dataModel]], params:params)

    } // equipmentRegisterFinancial

    def inventoryValueDetailedGsp = {
        render(view: 'inventoryValueDetailed')
    }

    def inventoryValueDetailed = {

        params.reportTitle = "Inventory Value Detailed"
        params.logoUrl = grailsApplication.mainContext.getResource('images/logo.png').getURL()
        params.currentUser = authService.currentUser

        def dataModel = inventoryReportService.getInventoryValueDetailed(params, RCU.getLocale(request))

        // Jasper plugin controller expects data to be a Collection.
        chain(controller:'jasper', action:'index', model:[data: [dataModel]], params:params)

    }

    def inventoryValueOverviewGsp = {
        render(view: 'inventoryValueOverview')
    }

    def inventoryValueOverview = {

        params.reportTitle = "Inventory Value Overview"
        params.logoUrl = grailsApplication.mainContext.getResource('images/logo.png').getURL()
        params.currentUser = authService.currentUser

        def dataModel = inventoryReportService.getInventoryValueOverview(params, RCU.getLocale(request))

        // Jasper plugin controller expects data to be a Collection.
        chain(controller:'jasper', action:'index', model:[data: [dataModel]], params:params)

    }

    def regulatoryRequirementsGsp = {
        render(view: 'regulatoryRequirements')
    }

    def regulatoryRequirements = {

        def result = assetReportService.getRegulatoryRequirements(params, RCU.getLocale(request))

        params.reportTitle = "Asset Regulatory Requirements"
        params.logoUrl = grailsApplication.mainContext.getResource('images/logo.png').getURL()
        params.currentUser = authService.currentUser
        params.startDateString = result.startDateString
        params.endDateString = result.endDateString

        if(!result.error) {
            // Jasper plugin controller expects data to be a Collection.
            chain(controller:'jasper', action:'index', model:[data: [result]], params:params)
            return
        }

        flash.errorMessage = g.message(code: result.error.code, args: result.error.args)
        redirect(action: 'regulatoryRequirementsGsp')

    } // regulatoryRequirements

    def mandatoryRequirementsGsp = {
        render(view: 'mandatoryRequirements')
    }

    def mandatoryRequirements = {

        def result = assetReportService.getMandatoryRequirements(params, RCU.getLocale(request))

        params.reportTitle = "Asset Mandatory Requirements"
        params.logoUrl = grailsApplication.mainContext.getResource('images/logo.png').getURL()
        params.currentUser = authService.currentUser
        params.startDateString = result.startDateString
        params.endDateString = result.endDateString

        if(!result.error) {
            // Jasper plugin controller expects data to be a Collection.
            chain(controller:'jasper', action:'index', model:[data: [result]], params:params)
            return
        }

        flash.errorMessage = g.message(code: result.error.code, args: result.error.args)
        redirect(action: 'mandatoryRequirementsGsp')

    } // mandatoryRequirements

} // end of class.
