

package gov.va.med.cds.util;


import gov.va.med.cds.exception.ErrorCodeEnum;
import gov.va.med.cds.exceptionframework.ExceptionHandler;
import gov.va.med.cds.filter.EntryFilterInterface;
import gov.va.med.cds.persistence.ReadException;

import java.util.Map;


public class TimeoutUtil
{
    public static final String UPPER_LIMIT_TIMEOUT = "upperLimitTimeout";


    public static Long processTimeout( Map<String, String> templateTimeoutMap, EntryFilterInterface entryFilter, String cdsAppName )
    {
        Long timeout = null;

        String timeoutStr = templateTimeoutMap.get( UPPER_LIMIT_TIMEOUT );
        try
        {
            timeout = new Long( timeoutStr );
        }
        catch ( Throwable t )
        {
            ExceptionHandler.handleException( new ReadException( ErrorCodeEnum.CANNOT_PARSE_TIMEOUT, t ), entryFilter.getTemplateId(),
                            entryFilter.getRequestId(), cdsAppName );
        }

        if ( entryFilter.getTimeout() != null )
        {
            if ( entryFilter.getTimeout() <= timeout )
            {
                timeout = entryFilter.getTimeout();
            }
            else
            {
                //TODO - send warning back to the client.
            }
        }
        else
        {
            timeoutStr = templateTimeoutMap.get( entryFilter.getTemplateId() + "-" + entryFilter.getDomainEntryPoint() );
            if ( timeoutStr != null )
            {
                Long configTimeout = new Long( timeoutStr );
                if ( configTimeout <= timeout )
                {
                    timeout = configTimeout;
                }
                else
                {
                    //TODO - send warning back to the client.
                }
            }
        }
        return timeout;
    }
}
