/*
 * Copyright (C) 2012  Bull S. A. S.
 * Bull, Rue Jean Jaures, B.P.68, 78340, Les Clayes-sous-Bois
 * This library is free software; you can redistribute it and/or modify it under the terms
 * of the GNU Lesser General Public License as published by the Free Software Foundation
 * version 2.1 of the License.
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Lesser General Public License for more details.
 * You should have received a copy of the GNU Lesser General Public License along with this
 * program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth
 * Floor, Boston, MA  02110-1301, USA.
 */

package org.ow2.jonas.cdi.weld.internal.services;

import javax.enterprise.inject.spi.InjectionPoint;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceUnit;

import org.jboss.weld.injection.spi.JpaInjectionServices;
import org.ow2.easybeans.persistence.api.EZBPersistenceUnitManager;

/**
 * Provides JPA related injection services
 *
 * @author Loic Albertin
 */
public class JOnASJpaInjectionServices implements JpaInjectionServices {

    private EZBPersistenceUnitManager persistenceUnitManager;

    public JOnASJpaInjectionServices(EZBPersistenceUnitManager persistenceUnitManager) {
        this.persistenceUnitManager = persistenceUnitManager;
    }

    public EntityManager resolvePersistenceContext(InjectionPoint injectionPoint) {
        PersistenceContext persistenceContext = injectionPoint.getAnnotated().getAnnotation(PersistenceContext.class);
        if (persistenceContext == null) {
            throw new IllegalStateException(
                    "Unable to resolve persistence context as injection point is not annotated with @PersistenceContext");
        }
        return persistenceUnitManager.getEntityManager(persistenceContext.name(), persistenceContext.type());
    }

    public EntityManagerFactory resolvePersistenceUnit(InjectionPoint injectionPoint) {
        PersistenceUnit persistenceUnit = injectionPoint.getAnnotated().getAnnotation(PersistenceUnit.class);
        if (persistenceUnit == null) {
            throw new IllegalStateException(
                    "Unable to resolve persistence context as injection point is not annotated with @PersistenceContext");
        }
        return persistenceUnitManager.getEntityManagerFactory(persistenceUnit.unitName());
    }

    public void cleanup() {
    }
}
