package zmo.technology.lite.components;

import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.env.PropertySource;
import org.springframework.web.context.support.StandardServletEnvironment;

import zmo.technology.lite.application.ZeroApplication;
import zmo.technology.lite.logging.ZeroLogger;

public class ZeroPreloadAdaptor implements ApplicationListener<ContextRefreshedEvent> {

    private ZeroPreloadAdaptor() {
        super();
    }

    public static ZeroPreloadAdaptor registerListener() {
        return new ZeroPreloadAdaptor();
    }

    @Override
    @SuppressWarnings("unchecked")
    public void onApplicationEvent(ContextRefreshedEvent event) {

        Properties properties = new Properties();
        StandardServletEnvironment environment = (StandardServletEnvironment) event.getApplicationContext()
                .getEnvironment();

        Iterator<PropertySource<?>> iterator = environment.getPropertySources().iterator();
        while (iterator.hasNext()) {
            PropertySource<?> source = iterator.next();
            if (source.getName().equals(StandardServletEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME) ||
                    source.getName().equals(StandardServletEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME) ||
                    !(source.getSource() instanceof Map))
                continue;
            properties.putAll(((Map<Object, Object>) source.getSource()));
        }

        ZeroApplication.initPropertys(properties);
        ZeroApplication.setContext(event.getApplicationContext());

        try {
            for (String beanName : ZeroApplication.getContext().getBeanDefinitionNames()) {
                Object beanObject = ZeroApplication.getContext().getBean(beanName);
                if (ZeroApplicationOnComplete.class.isAssignableFrom(beanObject.getClass()))
                    ((ZeroApplicationOnComplete) beanObject).onComplete();
            }
        } catch (Exception e) {
            ZeroLogger.SEVERE(e);
        }
    }

}
