/*-
 * ~~~~~~licensing~~~~~~
 * basic-auth-impl
 * ==========
 * Copyright (C) 2020 - 2021 EmDev LLC
 * ==========
 * 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.
 * ~~~~~~/licensing~~~~~~
 */
package ru.entaxy.esb.system.auth.basic.jpa.listener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SessionFactory;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.event.service.spi.EventListenerRegistry;
import org.hibernate.event.spi.EventType;

public class EntityEventListenerRegistry {

    private static final Log LOG = LogFactory.getLog(EntityEventListenerRegistry.class);
    private static final int SESSION_WAIT_TIMEOUT = 50000;

    private SessionFactory sessionFactory;
    private BasicAuthPostEventListener basicAuthPostEventListener;
    private int initLimiter = 0;


    public void registerListeners() {
        LOG.info("Init EntityEventListenerRegistry " + sessionFactory.getClass().getName());

        EventListenerRegistry registry = prepareRegistry();
        registry.getEventListenerGroup(EventType.POST_COMMIT_INSERT).appendListener(basicAuthPostEventListener);
        registry.getEventListenerGroup(EventType.POST_COMMIT_UPDATE).appendListener(basicAuthPostEventListener);
        registry.getEventListenerGroup(EventType.POST_COMMIT_DELETE).appendListener(basicAuthPostEventListener);
    }

    private EventListenerRegistry prepareRegistry() {
        try {
            SessionFactoryImplementor sessionFactoryImpl = sessionFactory.unwrap(SessionFactoryImplementor.class);
            EventListenerRegistry registry = sessionFactoryImpl.getServiceRegistry().getService(EventListenerRegistry.class);
            return registry;
        } catch (Exception e) {
            LOG.error(e.getMessage());
            if (initLimiter == 10) {
                LOG.error(e);
            }
            try {
                LOG.warn("Wait sessionFactory initialization...");
                Thread.sleep(SESSION_WAIT_TIMEOUT);
            } catch (InterruptedException e1) {
            }

        }
        return initLimiter++ <= 9
                ? prepareRegistry()
                : null;
    }


    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public BasicAuthPostEventListener getBasicAuthPostEventListener() {
        return basicAuthPostEventListener;
    }

    public void setBasicAuthPostEventListener(BasicAuthPostEventListener basicAuthPostEventListener) {
        this.basicAuthPostEventListener = basicAuthPostEventListener;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

}
