/*
 *
 * ====================================================================
 *
 * Copyright 2004 The Apache Software Foundation 
 *
 * Licensed 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.slide.projector.store;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.contract.Context;
import org.apache.commons.contract.Store;

public class CookieStore implements Store {
    public final static String ID = "cookies";

    protected HttpServletRequest request;
    protected HttpServletResponse response;

    public CookieStore(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        this.response = response;
    }

    public void put(String key, Object value, long timeout, Context context) {
        Cookie cookie = generateCookie(key, value);
        if ( cookie != null ) {
        	cookie.setMaxAge((int) (timeout/1000));
        	response.addCookie(cookie);
        }
    }

    public void put(String key, Object value, Context context) {
        Cookie cookie = generateCookie(key, value);
        if ( cookie != null ) {
            response.addCookie(cookie);
        }
    }

    private Cookie generateCookie(String key, Object value) {
        Cookie cookie = null;
        if ( value instanceof Cookie ) {
            cookie = (Cookie)value;
        } else {
            cookie = new Cookie(key, value.toString());
        }
        return cookie;
    }
    
    public Object get(String key, Context context) {
        Cookie[] cookies = request.getCookies();
        if ( cookies != null ) {
            for ( int i = 0; i < cookies.length; i++ ) {
                if ( cookies[i].getName().equals(key) ) {
                    return cookies[i].getValue();
                }
            }
        }
        return null;
    }

    public void dispose(String key, Context context) {
        request.removeAttribute(key);
    }

    public String getId() {
        return ID;
    }
}