package performa.utils;

import oneit.appservices.config.ConfigMgr;
import oneit.components.InitialisationParticipant;
import oneit.components.ParticipantInitialisationContext;
import oneit.logging.LogLevel;
import oneit.logging.LogMgr;
import oneit.logging.LoggingArea;
import oneit.objstore.ObjectTransaction;
import oneit.objstore.services.TransactionServicesFactory;
import oneit.servlets.utils.BaseHttpServletRequest;
import oneit.servlets.utils.BaseHttpServletResponse;
import oneit.servlets.utils.decorator.ServletDecorator;
import oneit.servlets.utils.decorator.ServletDecoratorConfig;
import oneit.utils.BusinessException;
import oneit.utils.InitialisationException;
import performa.orm.ShortenedURL;


public class ShortenedURLDecorator implements ServletDecorator, InitialisationParticipant
{
    public static final LoggingArea LOG             = LoggingArea.createLoggingArea("ShortenedURLFilter");
    public static final String      JOB_URL_PREFIX  = "/j/";
    
    @Override
    public void processRequest(ServletDecoratorConfig config, BaseHttpServletRequest request, BaseHttpServletResponse response) throws Exception
    {
        String  pathInfo    = request.getServletPath();
        
        LogMgr.log(LOG, LogLevel.PROCESSING1, "ShortenedURLFilter.doFilter: ", pathInfo);
        
        if (pathInfo != null && pathInfo.contains(JOB_URL_PREFIX))
        {   
            int     lastIndex   = pathInfo.lastIndexOf("/");
            String  shortcut    = pathInfo.substring(lastIndex+1);
                                 
            try
            {
                TransactionServicesFactory  servicesFactory =   (TransactionServicesFactory) ConfigMgr.getConfigObject(ConfigMgr.GLOBAL_CONFIG_SYSTEM, "TransactionServices");
                ObjectTransaction           objTran         =   new ObjectTransaction (servicesFactory);
                ShortenedURL[]              shortURL        =   ShortenedURL.searchByCode(objTran, shortcut);
                
                if(shortURL != null && shortURL.length > 0)
                {
                    request.setAttribute("DecoratorFilter.TERMINATE", "Yes");
                        
                    response.sendRedirect(shortURL[0].getUrlLink());                                
                }
            }
            catch (Exception e)
            {
                LogMgr.log(LOG, LogLevel.BUSINESS2, e, "Problem find the shorted url");
                throw new BusinessException("Something went wrong. Please contact Admin");
            }
        }
        config.forwardRequest(request, response);        
    }
    

    @Override
    public void init(ParticipantInitialisationContext context) throws InitialisationException
    {
        
    }
}