/* Copyright 2004-2005 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.codehaus.groovy.grails.orm.hibernate.cfg;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.groovy.grails.commons.*;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

import java.util.HashSet;
import java.util.Set;

/**
 * Allows configuring Grails' hibernate support to work in conjuntion with Hibernate's annotation
 * support
 *
 * @author Graeme Rocher
 * @since 18-Feb-2006
 */
public class GrailsAnnotationConfiguration  extends AnnotationConfiguration implements GrailsDomainConfiguration{
    private static final Log LOG  = LogFactory.getLog(GrailsAnnotationConfiguration.class);
    /**
     *
     */
    private static final long serialVersionUID = -7115087342689305517L;
    private GrailsApplication grailsApplication;
    private Set<GrailsDomainClass> domainClasses;
    private boolean configLocked;

    /**
     *
     */
    public GrailsAnnotationConfiguration() {
        super();
        this.domainClasses = new HashSet<GrailsDomainClass>();
    }

    /* (non-Javadoc)
      * @see org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsDomainConfiguration#addDomainClass(org.codehaus.groovy.grails.commons.GrailsDomainClass)
      */
    public GrailsDomainConfiguration addDomainClass( GrailsDomainClass domainClass ) {
        if(!AnnotationDomainClassArtefactHandler.isJPADomainClass(domainClass.getClazz())) {
            this.domainClasses.add(domainClass);
        }

        return this;
    }
    /* (non-Javadoc)
      * @see org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsDomainConfiguration#setGrailsApplication(org.codehaus.groovy.grails.commons.GrailsApplication)
      */
    public void setGrailsApplication(GrailsApplication application) {
        application.registerArtefactHandler(new AnnotationDomainClassArtefactHandler());
        this.grailsApplication = application;
        if(this.grailsApplication != null) {

            GrailsClass[] existingDomainClasses = this.grailsApplication.getArtefacts(DomainClassArtefactHandler.TYPE);
            for(int i = 0; i < existingDomainClasses.length;i++) {
                addDomainClass((GrailsDomainClass)existingDomainClasses[i]);
            }
        }
    }




    /* (non-Javadoc)
      * @see org.hibernate.cfg.Configuration#buildSessionFactory()
      */
    public SessionFactory buildSessionFactory() throws HibernateException {
        // set the class loader to load Groovy classes
        if(this.grailsApplication != null) {
        	if(LOG.isDebugEnabled()) {
        		LOG.debug("[GrailsAnnotationConfiguration] Setting context class loader to Grails GroovyClassLoader");
        	}
        	Thread.currentThread().setContextClassLoader( this.grailsApplication.getClassLoader() );        	
        }             

        SessionFactory sessionFactory =  super.buildSessionFactory();
        return sessionFactory;
    }

    /**
     *  Overrides the default behaviour to including binding of Grails
     *  domain classes
     */
    protected void secondPassCompile() throws MappingException {
        if (configLocked) {
            return;
        }
        if(LOG.isDebugEnabled()) {
        	LOG.debug("[GrailsAnnotationConfiguration] [" + this.domainClasses.size() + "] Grails domain classes to bind to persistence runtime");
		}

        // do Grails class configuration
        for (GrailsDomainClass domainClass : this.domainClasses) {
            GrailsDomainBinder.evaluateMapping(domainClass);
        }

        // do Grails class configuration
        for (GrailsDomainClass domainClass : this.domainClasses) {          
            if (LOG.isDebugEnabled()) {
                LOG.debug("[GrailsAnnotationConfiguration] Binding persistent class [" + domainClass.getFullName() + "]");
            }
            GrailsDomainBinder.bindClass(domainClass, super.createMappings());
        }

        // call super
        super.secondPassCompile();
        this.configLocked = true;
    }

}

@@ -3817,16 +3817,17 @@
     if (
+!
 configLo
@@ -3842,34 +3842,8 @@
     
-        return;%0A        %7D%0A
     
@@ -3881,17 +3881,24 @@
         
-%09
+        
 LOG.debu
@@ -4028,13 +4028,27 @@
 %22);%0A
-%09%09%7D%0A%0A
+            %7D%0A%0A    
     
@@ -4084,32 +4084,36 @@
 uration%0A        
+    
 for (GrailsDomai
@@ -4159,32 +4159,36 @@
 ) %7B%0A            
+   
+ 
 GrailsDomainBind
@@ -4220,32 +4220,36 @@
 Class);%0A        
+    
 %7D%0A%0A        // do
@@ -4235,32 +4235,36 @@
      %7D%0A%0A        
+  
+  
 // do Grails cla
@@ -4272,32 +4272,36 @@
 s configuration%0A
+    
         for (Gra
@@ -4354,21 +4354,16 @@
 s) %7B
-   
+%0A
        
-%0A  
     
@@ -4363,25 +4363,24 @@
             
- 
 if (LOG.isDe
@@ -4387,32 +4387,36 @@
 bugEnabled()) %7B%0A
+    
                 
@@ -4526,34 +4526,42 @@
 %22);%0A            
-%7D%0A
+    %7D%0A    
             Grai
@@ -4619,24 +4619,38 @@
 appings());%0A
+            %7D%0A
         %7D%0A%0A 

fix for GRAILS-5156 "GrailsAnnotationConfiguration overrides and completely locks repeated calling super.secondPassCompile() method"