package com.atlassian.confluence.extra.userlister;

import com.atlassian.confluence.event.EventListener;
import com.atlassian.confluence.event.events.ConfluenceEvent;
import com.atlassian.confluence.event.events.security.LoginEvent;
import com.atlassian.confluence.event.events.security.LogoutEvent;
import com.atlassian.confluence.event.events.security.LoginFailedEvent;
import com.atlassian.plugin.PluginManager;
import bucket.container.ContainerManager;

import java.util.List;

public class UserListener implements EventListener
{
    private UserLister userLister;
    private PluginManager pluginManager;

    Class[] handledClasses = new Class[]{ LoginEvent.class, LogoutEvent.class, LoginFailedEvent.class};

    public void handleEvent(ConfluenceEvent event)
    {
        if (event instanceof LoginEvent)
        {
            LoginEvent loginEvent = (LoginEvent) event;
            getUserLister().userLoggedIn(loginEvent.getUsername(), loginEvent.getSessionId());
        }
        else if (event instanceof LogoutEvent)
        {
            LogoutEvent logoutEvent = (LogoutEvent) event;
            getUserLister().userLoggedOut(logoutEvent.getSessionId());
        }

//        else if (event instanceof LoginFailedEvent)
//        {
//            LoginFailedEvent loginFailedEvent = (LoginFailedEvent) event;
//        }
    }

    public UserLister getUserLister()
    {
        if (userLister == null)
        {
            if (pluginManager == null)
            {
                pluginManager = (PluginManager) ContainerManager.getInstance().getContainerContext().getComponent("pluginManager");
            }
            List pluginModulesEnabledByClass = pluginManager.getEnabledModulesByClass(com.atlassian.confluence.extra.userlister.UserLister.class);

            userLister = (UserLister) pluginModulesEnabledByClass.get(0);

            if (userLister == null)
                throw new RuntimeException("Could not load com.atlassian.confluence.extra.userlister.UserLister from PluginManager" );
        }

        return userLister;
    }

    public Class[] getHandledEventClasses()
    {
        return handledClasses;
    }
}
