import org.codehaus.groovy.grails.plugins.springsecurity.Secured

/**
* Controller class for the application core views.
*/
class AppCoreController extends BaseController {

    def personService
    def createDataService
    def appConfigService

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

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

    /**
    * This is where we arrive after login.
    *  Attach the welcome flash message and redirect to where ever we want the user to start.
    * e.g. redirect(controller:"taskDetailed", action:"search")
    */
    def welcome = {
        def personInstance = personService.currentUser
        flash.message = "Welcome, ${personInstance.firstName} ${personInstance.lastName}."

        def sess = getSession()
        sess.setMaxInactiveInterval(personInstance.sessionTimeout)
        redirect(action:start)
    }

    /**
    * Render the start view.
    */
    def start = {
    }

    /**
    * Allow a person to change their session timeout setting.
    */
    def changeSessionTimeout = {
        if (request.method == 'GET') {
            def personInstance = personService.currentUser
            return [ personInstance : personInstance ]       
        }
        if (request.method == 'POST') {
            def personInstance = personService.currentUser
                personInstance.properties = params
                if (!personInstance.hasErrors() && personInstance.save(flush: true)) {
                    def sess = getSession()
                    sess.setMaxInactiveInterval(personInstance.sessionTimeout)
                    flash.message = "Session timeout changed."
                    redirect(action:start)
                }
                else {
                    render(view:'changeSessionTimeout',model:[personInstance:personInstance])
                }
        }
    }

    /**
    * Allow a person to change their password.
    */
    def changePassword = {
        //def principal = authenticateService.principal()
        //println principal.getAuthorities()

        if (request.method == 'GET') {
            def personInstance = personService.currentUser
            return [ personInstance : personInstance ]       
        }

        if (request.method == 'POST') {
            def personInstance = personService.currentUser

            if(params.confirmPass == params.pass) {
                personInstance.pass = params.pass
                personInstance.password = authenticateService.encodePassword(personInstance.pass)

                if (!personInstance.hasErrors() && personInstance.save(flush: true)) {
                    //userCache.removeUserFromCache(personInstance.loginName)
                    flash.message = "Password changed successfully."
                    redirect(action:start)
                }
                else {
                    render(view:'changePassword',model:[personInstance:personInstance])
                }
            }
            else {
                personInstance.errors.reject('person.pass.doesNotMatch',            // Error code, see grails-app/i18n/message.properties
                                                                ['pass', 'class Person'].toArray(),      // Groovy ListArray cast to Object[]
                                                                 '[NothingUseMessageProperites]')  // Default mapping string.
                render(view:'changePassword',model:[personInstance:personInstance])
            }

        }
    }

    /**
    * Render the manager view for manager or admin roles.
    */
    @Secured(['ROLE_Manager','ROLE_AppAdmin'])
    def manager = {
    }

    /**
    * Render the appAdmin view for admin roles.
    */
    @Secured(['ROLE_AppAdmin'])
    def appAdmin = {

        def offerBaseDataCreation = false
        def offerDemoDataCreation = false
        def baseDataCreated = appConfigService.exists("baseDataCreated")
        def demoDataCreated = appConfigService.exists("demoDataCreated")
        def demoDataCreationDisabled = appConfigService.exists("demoDataCreationDisabled")

        if(!baseDataCreated)
            offerBaseDataCreation = true

        if(baseDataCreated && !demoDataCreated && !demoDataCreationDisabled)
            offerDemoDataCreation = true

        return[baseDataCreated: baseDataCreated,
                        demoDataCreated: demoDataCreated,
                        offerDemoDataCreation: offerDemoDataCreation,
                        offerBaseDataCreation: offerBaseDataCreation,
                        demoDataCreationDisabled: demoDataCreationDisabled]
    }

    /**
    * Allow admin to disable demo data creation.
    */
    @Secured(['ROLE_AppAdmin'])
    def disableDemoDataCreation = {
        if(!appConfigService.set("demoDataCreationDisabled")) {
            flash.message = "Demo data creation could not be disabled."
            redirect(action: appAdmin)
            return
        }

        // Success.
        flash.message = "Demo data creation disabled."
        redirect(action: appAdmin)
    }

    /**
    * Allow admin to create base data.
    */
    @Secured(['ROLE_AppAdmin'])
    def createBaseData = {
        if(!createDataService.createBaseData()) {
            flash.message = "Base data could not be created."
            redirect(action: appAdmin)
            return
        }

        // Success.
        flash.message = "Base data created."
        redirect(action: appAdmin)
    }

    /**
    * Allow admin to create demo data.
    */
    @Secured(['ROLE_AppAdmin'])
    def createDemoData = {
        if(!createDataService.createDemoData()) {
            flash.message = "Demo data could not be created."
            redirect(action: appAdmin)
            return
        }

        // Success.
        flash.message = "Demo data created."
        redirect(action: appAdmin)
    }

} // end of class.
