/*
 * Copyright 2014-2015 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.griffon.runtime.hibernate5;

import griffon.plugins.hibernate5.Hibernate5Callback;
import griffon.plugins.hibernate5.Hibernate5Factory;
import griffon.plugins.hibernate5.Hibernate5Handler;
import griffon.plugins.hibernate5.Hibernate5Storage;
import griffon.plugins.hibernate5.exceptions.RuntimeHibernate5Exception;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.resource.transaction.spi.TransactionStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.inject.Inject;

import static griffon.util.GriffonNameUtils.requireNonBlank;
import static java.util.Objects.requireNonNull;

/**
 * @author Andres Almiray
 */
public class DefaultHibernate5Handler implements Hibernate5Handler {
    private static final Logger LOG = LoggerFactory.getLogger(DefaultHibernate5Handler.class);
    private static final String ERROR_SESSION_FACTORY_NAME_BLANK = "Argument 'sessionFactoryName' must not be blank";
    private static final String ERROR_CALLBACK_NULL = "Argument 'callback' must not be null";

    private final Hibernate5Factory hibernate5Factory;
    private final Hibernate5Storage hibernate5Storage;

    @Inject
    public DefaultHibernate5Handler(@Nonnull Hibernate5Factory hibernate5Factory, @Nonnull Hibernate5Storage hibernate5Storage) {
        this.hibernate5Factory = requireNonNull(hibernate5Factory, "Argument 'hibernate5Factory' must not be null");
        this.hibernate5Storage = requireNonNull(hibernate5Storage, "Argument 'hibernate5Storage' must not be null");
    }

    @Nullable
    @Override
    public <R> R withHbm5Session(@Nonnull Hibernate5Callback<R> callback) throws RuntimeHibernate5Exception {
        return withHbm5Session(DefaultHibernate5Factory.KEY_DEFAULT, callback);
    }

    @Nullable
    @Override
    @SuppressWarnings("ThrowFromFinallyBlock")
    public <R> R withHbm5Session(@Nonnull String sessionFactoryName, @Nonnull Hibernate5Callback<R> callback) throws RuntimeHibernate5Exception {
        requireNonBlank(sessionFactoryName, ERROR_SESSION_FACTORY_NAME_BLANK);
        requireNonNull(callback, ERROR_CALLBACK_NULL);

        SessionFactory sf = getSessionFactory(sessionFactoryName);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Executing statements on session '{}'", sessionFactoryName);
        }
        Session session = sf.openSession();
        try {
            session.beginTransaction();
            return callback.handle(sessionFactoryName, session);
        } catch (Exception e) {
            throw new RuntimeHibernate5Exception(sessionFactoryName, e);
        } finally {
            try {
                if (session.getTransaction().getStatus()!= TransactionStatus.ROLLED_BACK) {
                    session.getTransaction().commit();
                }
                session.close();
            } catch (Exception e) {
                throw new RuntimeHibernate5Exception(sessionFactoryName, e);
            }
        }
    }

    @Override
    public void closeHbm5Session() {
        closeHbm5Session(DefaultHibernate5Factory.KEY_DEFAULT);
    }

    @Override
    public void closeHbm5Session(@Nonnull String sessionFactoryName) {
        requireNonBlank(sessionFactoryName, ERROR_SESSION_FACTORY_NAME_BLANK);
        SessionFactory hibernate5 = hibernate5Storage.get(sessionFactoryName);
        if (hibernate5 != null) {
            hibernate5Factory.destroy(sessionFactoryName, hibernate5);
            hibernate5Storage.remove(sessionFactoryName);
        }
    }

    @Nonnull
    private SessionFactory getSessionFactory(@Nonnull String sessionFactoryName) {
        SessionFactory sessionFactory = hibernate5Storage.get(sessionFactoryName);
        if (sessionFactory == null) {
            sessionFactory = hibernate5Factory.create(sessionFactoryName);
            hibernate5Storage.set(sessionFactoryName, sessionFactory);
        }
        return sessionFactory;
    }
}

@@ -1041,33 +1041,8 @@
 ate.
-resource.transaction.spi.
 Tran
@@ -1048,22 +1048,16 @@
 nsaction
-Status
 ;%0Aimport
@@ -2799,17 +2799,16 @@
 _NULL);%0A
-%0A
         
@@ -3025,51 +3025,133 @@
 n = 
-sf.openSession();%0A        try %7B%0A           
+null;%0A        Transaction transaction = null;%0A        try %7B%0A            session = sf.openSession();%0A            transaction =
  ses
@@ -3187,22 +3187,26 @@
         
-return
+R result =
  callbac
@@ -3256,340 +3256,539 @@
     
-%7D catch (Exception e) %7B%0A            throw new RuntimeHibernate5Exception(sessionFactoryName, e);%0A        %7D finally %7B%0A            try %7B%0A                if (session.getTransaction().getStatus()!= TransactionStatus.ROLLED_BACK) %7B%0A                    session.getTransaction().commit();%0A                %7D%0A                session.close();
+    transaction.commit();%0A            return result;%0A        %7D catch (Exception e) %7B%0A            try %7B%0A                if (transaction != null)%0A                    transaction.rollback();%0A            %7D catch (RuntimeException runtimeException) %7B%0A                LOG.error(%22Failed to rollback%22, runtimeException);%0A            %7D%0A            throw new RuntimeHibernate5Exception(sessionFactoryName, e);%0A        %7D finally %7B%0A            try %7B%0A                if (session != null) %7B%0A                    session.close();%0A                %7D
 %0A   

Change of how exception in transaction is handled