/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */
package org.apache.jetspeed.aggregator.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.BooleanUtils;
import org.apache.jetspeed.PortalReservedParameters;
import org.apache.jetspeed.aggregator.PortletTrackingManager;
import org.apache.jetspeed.aggregator.RenderTrackable;
import org.apache.jetspeed.container.PortletWindow;
import org.apache.jetspeed.om.portlet.LocalizedField;
import org.apache.jetspeed.om.portlet.PortletDefinition;

/**
 * Tracks out of service status for portlets
 *  
 * @author <a href="mailto:taylor@apache.org">David Sean Taylor</a>
 * @version $Id$
 */
public class PortletTrackingManagerImpl implements PortletTrackingManager
{
    protected Map outOfService = Collections.synchronizedMap(new HashMap());

    /**
     * when rendering a portlet, the default timeout period in milliseconds
     * setting to zero will disable (no timeout) the timeout
     *  
     */
    protected long defaultPortletTimeout; 
    
    /**
     * Out of service limit, if a portlet entity times out past its limit (or default limit) n consecutive times, 
     * it is taken out of service
     */
    protected int outOfServiceLimit;
    
    public PortletTrackingManagerImpl(long defaultPortletTimeout, int outOfServiceLimit)
    {
        this.defaultPortletTimeout = defaultPortletTimeout;
        this.outOfServiceLimit = outOfServiceLimit;
    }
    
    public long getDefaultPortletTimeout()
    {
        return this.defaultPortletTimeout;
    }

    public boolean exceededTimeout(long renderTime, PortletWindow window)
    {
        RenderTrackable trackInfo = (RenderTrackable)window;
        long defaultTimeout = this.getDefaultPortletTimeout();
        if (trackInfo.getExpiration() > 0)
        {
            return (renderTime > trackInfo.getExpiration());
        }
        else if (defaultTimeout > 0)
        {
            return (renderTime > defaultTimeout);
        }
        return false;
    }
    
    public boolean isOutOfService(PortletWindow window)
    {
        RenderTrackable trackable = (RenderTrackable)window;
        if (trackable.getRenderTimeoutCount() > this.outOfServiceLimit)
        {
            return true;
        }
        
        PortletDefinition def = window.getPortletDefinition();
        Collection<LocalizedField> fields = def.getMetadata().getFields(PortalReservedParameters.PORTLET_EXTENDED_DESCRIPTOR_OUT_OF_SERVICE);
        
        if (fields != null && !fields.isEmpty())
        {
            if (BooleanUtils.toBoolean(fields.iterator().next().getValue()))
            {
                return true;
            }
        }
        
        return false;
    }
    
    public int getOutOfServiceLimit()
    {
        return this.outOfServiceLimit;
    }
    
    public void incrementRenderTimeoutCount(PortletWindow window)
    {
        RenderTrackable trackable = (RenderTrackable)window;
        trackable.incrementRenderTimeoutCount();       
    }
   
    public void success(PortletWindow window)
    {
        RenderTrackable trackable = (RenderTrackable)window;
        trackable.success();
    }
    
    public void setExpiration(PortletWindow window, long expiration)
    {
        RenderTrackable trackable = (RenderTrackable)window;
        trackable.setExpiration(expiration); // * 1000);                
    }
        
    public void takeOutOfService(PortletWindow window)
    {
        RenderTrackable trackable = (RenderTrackable)window;
        trackable.setRenderTimeoutCount((int)this.defaultPortletTimeout + 1);
    }
    
    public void putIntoService(PortletWindow window)
    {
        RenderTrackable trackable = (RenderTrackable)window;
        trackable.setRenderTimeoutCount(0);        
    }
    
    public void putIntoService(List fullPortletNames)
    {
        // TODO
    }
    
    public List getOutOfServiceList(String fullPortletName)
    {
        List outs = new ArrayList();
        // TODO
        return outs;
    }
    
    public List getOutOfServiceList()
    {
        List outs = new ArrayList();
        // TODO
        return outs;
    }
}