import grails.util.GrailsUtil

class BootStrap 
{
    //Required to be right here for Acegi plugin.
    def authenticateService
    Boolean BootStrapDemoDataSuccessful = true

    def init = { servletContext ->

    println "**** BootStrap GrailsUtil.environment = ${GrailsUtil.environment}"
    
        switch (GrailsUtil.environment)
        {
            case "development":
                        bootStrapDemoData()
                        break
            case "test":
                        break
            case "production":
                        bootStrapDemoData()
                        break 
        }
    
    }

    def destroy = {
    }

    //Insert some demo/startup data.
    void bootStrapDemoData()
    {
        println "BootStrapping demo data..."
    
        //TypeOfPersonGroup
	def personGroupTypeInstance
        personGroupTypeInstance = new PersonGroupType(name:"Department")
	BootStrapSaveAndTest(personGroupTypeInstance)
        personGroupTypeInstance = new PersonGroupType(name:"Contractor")
	BootStrapSaveAndTest(personGroupTypeInstance)
        personGroupTypeInstance = new PersonGroupType(name:"ProjectTeam")
	BootStrapSaveAndTest(personGroupTypeInstance)
    
        //PersonGroup
	def personGroupInstance
        personGroupInstance = new PersonGroup(personGroupType:PersonGroupType.findByName("Department"),
                        name:"Electrical")
	BootStrapSaveAndTest(personGroupInstance)
        personGroupInstance = new PersonGroup(personGroupType:PersonGroupType.findByName("Department"),
                        name:"Mechanical")
	BootStrapSaveAndTest(personGroupInstance)
        personGroupInstance = new PersonGroup(personGroupType:PersonGroupType.findByName("Department"),
                        name:"Production")
	BootStrapSaveAndTest(personGroupInstance)
        personGroupInstance = new PersonGroup(personGroupType:PersonGroupType.get(2),
                        name:"Kewl AirCon Guys")
	BootStrapSaveAndTest(personGroupInstance)
        personGroupInstance = new PersonGroup(personGroupType:PersonGroupType.get(3),
                        name:"gnuMims")
	BootStrapSaveAndTest(personGroupInstance)

        //Authority
        def authInstance

        authInstance = new Authority(description:"Application Admin, grants full admin access to the application.",
                                        authority:"ROLE_AppAdmin")
        BootStrapSaveAndTest(authInstance)

        authInstance = new Authority(description:"Business manager, grants full management access.",
                                        authority:"ROLE_Manager")
        BootStrapSaveAndTest(authInstance)

        authInstance = new Authority(description:"Application User, all application users need this base role to allow login.",
                                        authority:"ROLE_AppUser")
        BootStrapSaveAndTest(authInstance)
            
        //Person
        def passClearText = "pass"
        def passwordEncoded = authenticateService.encodePassword(passClearText)
        def personInstance

        personInstance = new Person(loginName:"admin",
                                    firstName:"Admin",
                                    lastName:"Powers",
                                    pass:passClearText,
                                    password:passwordEncoded,
                                    email:"admin@example.com")
        BootStrapSaveAndTest(personInstance)
        personInstance.addToAuthorities(Authority.get(1))
        personInstance.addToAuthorities(Authority.get(2))
        personInstance.addToAuthorities(Authority.get(3))
        personInstance.addToPersonGroups(PersonGroup.findByName("gnuMims"))

        personInstance = new Person(loginName:"manager",
                                    firstName:"Meca",
                                    lastName:"Manager",
                                    pass:passClearText,
                                    password:passwordEncoded,
                                    email:"manager@example.com")
        BootStrapSaveAndTest(personInstance)
        personInstance.addToAuthorities(Authority.get(2))
        personInstance.addToAuthorities(Authority.get(3))
        personInstance.addToPersonGroups(PersonGroup.findByName("gnuMims"))

        personInstance = new Person(loginName:"user",
                                    firstName:"Demo",
                                    lastName:"Danza",
                                    pass:passClearText,
                                    password:passwordEncoded,
                                    email:"user@example.com")
        BootStrapSaveAndTest(personInstance)
        personInstance.addToAuthorities(Authority.get(3))
        personInstance.addToPersonGroups(PersonGroup.findByName("Electrical"))

        personInstance = new Person(loginName:"craig",
                                    firstName:"Craig",
                                    lastName:"SuperTech",
                                    pass:passClearText,
                                    password:passwordEncoded,
                                    email:"user@example.com")
        BootStrapSaveAndTest(personInstance)
        personInstance.addToAuthorities(Authority.get(3))
        personInstance.addToPersonGroups(PersonGroup.findByName("Electrical"))

        personInstance = new Person(loginName:"john",
                                    firstName:"John",
                                    lastName:"Samples",
                                    pass:passClearText,
                                    password:passwordEncoded,
                                    email:"user@example.com")
        BootStrapSaveAndTest(personInstance)
        personInstance.addToAuthorities(Authority.get(3))
        personInstance.addToPersonGroups(PersonGroup.findByName("Mechanical"))

        personInstance = new Person(loginName:"mann",
                                    firstName:"Production",
                                    lastName:"Mann",
                                    pass:passClearText,
                                    password:passwordEncoded,
                                    email:"user@example.com")
        BootStrapSaveAndTest(personInstance)
        personInstance.addToAuthorities(Authority.get(3))
        personInstance.addToPersonGroups(PersonGroup.findByName("Production"))

        //TaskGroup
        def taskGroupInstance

        taskGroupInstance = new TaskGroup(name:"Engineering Activites",
                      description:"Engineering daily activities")
        BootStrapSaveAndTest(taskGroupInstance)

        taskGroupInstance = new TaskGroup(name:"Production Activites",
                      description:"Production daily activities")
        BootStrapSaveAndTest(taskGroupInstance)

        taskGroupInstance = new TaskGroup(name:"New Projects",
                      description:" ")
        BootStrapSaveAndTest(taskGroupInstance)

        //TaskStatus
        def taskStatusInstance
    
        taskStatusInstance = new TaskStatus(name:"Not Started")
        BootStrapSaveAndTest(taskStatusInstance)

        taskStatusInstance = new TaskStatus(name:"In Progress")
        BootStrapSaveAndTest(taskStatusInstance)

        taskStatusInstance = new TaskStatus(name:"Completed")
        BootStrapSaveAndTest(taskStatusInstance)

        //TaskPriority
        def taskPriorityInstance

        taskPriorityInstance = new TaskPriority(name:"Low")
        BootStrapSaveAndTest(taskPriorityInstance)

        taskPriorityInstance = new TaskPriority(name:"Normal")
        BootStrapSaveAndTest(taskPriorityInstance)

        taskPriorityInstance = new TaskPriority(name:"High")
        BootStrapSaveAndTest(taskPriorityInstance)

        taskPriorityInstance = new TaskPriority(name:"Immediate")
        BootStrapSaveAndTest(taskPriorityInstance)

        //TaskType
        def taskTypeInstance

        taskTypeInstance = new TaskType(name:"Unscheduled Breakin")
        BootStrapSaveAndTest(taskTypeInstance)

        taskTypeInstance = new TaskType(name:"Planned Maintenance")
        BootStrapSaveAndTest(taskTypeInstance)

        taskTypeInstance = new TaskType(name:"Project")
        BootStrapSaveAndTest(taskTypeInstance)

        taskTypeInstance = new TaskType(name:"Turnaround")
        BootStrapSaveAndTest(taskTypeInstance)

        taskTypeInstance = new TaskType(name:"Production Run")
        BootStrapSaveAndTest(taskTypeInstance)

        //Task
        def taskInstance
        def subTaskInstance

        taskInstance = new Task(taskGroup:TaskGroup.findByName("Engineering Activites"),
                 taskStatus:TaskStatus.findByName("Not Started"),
                 taskPriority:TaskPriority.get(2),
                 taskType:TaskType.get(1),
                 leadPerson:Person.get(3),
                 description:"Check specific level sensor",
                 comment:"Has been noted as problematic, try recallibrating")
        BootStrapSaveAndTest(taskInstance)

        subTaskInstance = new Task(taskGroup:TaskGroup.findByName("Engineering Activites"),
                 taskStatus:TaskStatus.findByName("Not Started"),
                 taskPriority:TaskPriority.get(2),
                 taskType:TaskType.get(1),
                 leadPerson:Person.get(3),
                 description:"Some follow up work",
                 comment:"Some help required")
        BootStrapSaveAndTest(subTaskInstance)
        
        //Add task 2 as a subTask of task 1.
        taskInstance.addToSubTasks(Task.get(2))
        subTaskInstance.parentTask = Task.get(1)

        subTaskInstance = new Task(taskGroup:TaskGroup.findByName("Engineering Activites"),
                 taskStatus:TaskStatus.findByName("Not Started"),
                 taskPriority:TaskPriority.get(2),
                 taskType:TaskType.get(1),
                 leadPerson:Person.get(3),
                 description:"Replace sensor at next opportunity.",
                 comment:"Nothing else has worked.")
        BootStrapSaveAndTest(subTaskInstance)

        //Add task 3 as a subTask of task 1.
        taskInstance.addToSubTasks(Task.get(3))
        subTaskInstance.parentTask = Task.get(1)

        taskInstance = new Task(taskGroup:TaskGroup.findByName("Production Activites"),
                 taskStatus:TaskStatus.findByName("Not Started"),
                 taskPriority:TaskPriority.get(2),
                 taskType:TaskType.get(5),
                 leadPerson:Person.get(5),
                 description:"Production Report",
                 comment:"Production report for specific production run or shift")
        BootStrapSaveAndTest(taskInstance)

        taskInstance = new Task(taskGroup:TaskGroup.findByName("New Projects"),
                 taskStatus:TaskStatus.findByName("Not Started"),
                 taskPriority:TaskPriority.get(2),
                 taskType:TaskType.get(3),
                 leadPerson:Person.get(1),
                 description:"Make killer CMMS app",
                 comment:"Use Grails and get a move on!")
        BootStrapSaveAndTest(taskInstance)

        //EntryType
        def entryTypeInstance

        entryTypeInstance = new EntryType(name:"Fault")
        BootStrapSaveAndTest(entryTypeInstance)

        entryTypeInstance = new EntryType(name:"WorkDone")
        BootStrapSaveAndTest(entryTypeInstance)

        entryTypeInstance = new EntryType(name:"Production Note")
        BootStrapSaveAndTest(entryTypeInstance)

        entryTypeInstance = new EntryType(name:"Work Request")
        BootStrapSaveAndTest(entryTypeInstance)

        //Entry
        def entryInstance

        entryInstance = new Entry(enteredBy: Person.get(6),
                                                    task: Task.get(1),
                                                    entryType: EntryType.findByName("Fault"),
                                                    comment: "This level sensor is causing us trouble.",
                                                    durationMinute: 20)
        BootStrapSaveAndTest(entryInstance)

        entryInstance = new Entry(enteredBy: Person.get(4),
                                                    task: Task.get(1),
                                                    entryType: EntryType.findByName("WorkDone"),
                                                    comment: "Cleaned sensor, see how it goes.",
                                                    durationMinute: 30)
        BootStrapSaveAndTest(entryInstance)

        entryInstance = new Entry(enteredBy: Person.get(4),
                                                    task: Task.get(1),
                                                    entryType: EntryType.findByName("WorkDone"),
                                                    comment: "Checked up on it later and sensor is dropping out intermittently, created subTask to replace sensor.",
                                                    durationMinute: 20)
        BootStrapSaveAndTest(entryInstance)

        //ModificationType
        def taskModificationTypeInstance
        taskModificationTypeInstance = new TaskModificationType(name:"Created").save()
        taskModificationTypeInstance = new TaskModificationType(name:"Completed").save()
        taskModificationTypeInstance = new TaskModificationType(name:"Closed").save()
        taskModificationTypeInstance = new TaskModificationType(name:"Altered").save()
        taskModificationTypeInstance = new TaskModificationType(name:"TargetDateModified").save()
        taskModificationTypeInstance = new TaskModificationType(name:"ScheduledDateModified").save()
        taskModificationTypeInstance = new TaskModificationType(name:"DescriptionModified").save()
        taskModificationTypeInstance = new TaskModificationType(name:"AssignedToModified").save()
        taskModificationTypeInstance = new TaskModificationType(name:"NameModified").save()
    
        //AssignedPerson
        def assignedPersonInstance

        assignedPersonInstance = new AssignedPerson(person: Person.get(4),
                                                                                        task: Task.get(1),
                                                                                        estimatedHour: 1,
                                                                                        estimatedMinute: 20)
        BootStrapSaveAndTest(assignedPersonInstance)

        assignedPersonInstance = new AssignedPerson(person: Person.get(5),
                                                                                        task: Task.get(1),
                                                                                        estimatedHour: 3,
                                                                                        estimatedMinute: 30)
        BootStrapSaveAndTest(assignedPersonInstance)


        //Finally did it all work.        
        if(BootStrapDemoDataSuccessful) {
            println "BootStrapping demo data...successful."
        }
        else println "BootStrapping demo data...failed."
    }
    
    void BootStrapSaveAndTest(object) {
        if(!object.save()) {
            BootStrapDemoDataSuccessful = false
            println "'${object}' failed to save!"
            println object.errors

        }
    } 
}
