/*
 * $Id: IsCategoryCreatorTag.java,v 1.2 2006/03/23 11:45:57 marbobo Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 * $Log: IsCategoryCreatorTag.java,v $
 * Revision 1.2  2006/03/23 11:45:57  marbobo
 * + Mögliche NPE abgefangen
 *
 * Revision 1.1  2005/08/09 19:01:21  jonyp
 * *** empty log message ***
 *
 * 
 */

package vkc.view.tag;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.TagSupport;

import vkc.db.entities.VKCUser;
import vkc.db.entities.VKCCategory;
import vkc.exception.DBException;
import vkc.db.serializer.VKCCategorySerializer;
import vkc.util.ServletUtils;
import vkc.view.WebShare;

/**
 * Tag zur Überprüfung, ob der aktuelle User der Erzeuger dieser Kategorie ist
 *
 * @author jonyP
 */
public class IsCategoryCreatorTag extends TagSupport{
    private Integer categoryId = null;

    private String value = "true";
    
    public IsCategoryCreatorTag() {
    }
    
    public void setValue(String value) {
        this.value = value;
    }

    public void setCategoryId(Integer categoryId) {
        this.categoryId = categoryId;
    }
    
    private boolean isCategoryCreator() throws JspTagException {
        VKCUser user = ServletUtils.getUser((HttpServletRequest)pageContext.getRequest());

        if (user == null) {
           throw new JspTagException("A User object in session scope not found! (KEY=" + WebShare.USER_KEY + ")");
        }
       
        try {
            if (!user.hasAdminPrivileges()) {
	        	VKCCategory category = VKCCategorySerializer.retrieveCategory(this.categoryId);
	            
	        	/*   creator=user   value      return
	        	 *      false       false       true
	        	 *      false       true        false
	        	 *      true        false       false
	        	 *      true        true        true 
	        	 */
	            if (("true".equals(this.value) && (category.getCategoryId().intValue() == user.getUserId().intValue()))
	            	|| ("false".equals(this.value) && (category.getCategoryId().intValue() != user.getUserId().intValue()))) {
	            	return true;
                }

	            return false;
            } 

           	return true;
        } catch (DBException ex) {
        }
        
        return false;
    }

    /**
     * Aufruf der Methode am Anfang des Tags
     */
    public int doStartTag() throws JspException {
        if (isCategoryCreator()) {   
		    return EVAL_BODY_INCLUDE;
		} 
        
        return SKIP_BODY;
    }

    /**
     * Aufruf der Methode am Ende des Tags
     */
    public int doEndTag() throws JspException {
		return EVAL_PAGE;
    }
}