/*
 * $Id: CreateProjectForm.java,v 1.1 2006/10/04 03:14:46 marbobo Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 * 
 * $Log: CreateProjectForm.java,v $
 * Revision 1.1  2006/10/04 03:14:46  marbobo
 * + Vollständige Unterstützung für Templates implementiert
 * + Alles von Virtoweb auf ProCoBa umgestellt
 *
 * Revision 1.8  2004/11/10 15:02:49  koppy
 * Projektweite Überarbeitung von Error-Logs, Stacktraces,..
 *
 * Revision 1.7  2004/10/31 03:04:39  marbobo
 * + Refactoring
 *
 * Revision 1.6  2004/10/26 22:30:03  marbobo
 * + kleine Anpassung
 *
 * Revision 1.5  2004/07/20 09:00:51  jonyp
 * added copyright info + cvs log
 *
 */

package vkc.procoba.project;

import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import vkc.db.entities.VKCCategory;
import vkc.db.entities.VKCSubCategory;
import vkc.db.entities.VKCCatProjectStep;
import vkc.db.serializer.VKCCategorySerializer;
import vkc.exception.DBException;
import vkc.misc.VKCLogManager;
import vkc.util.CategoryUtils;
import vkc.util.DateUtils;
import vkc.util.StringUtils;
import vkc.view.InputFieldConstraints;
import vkc.view.PageId;
import vkc.view.WebShare;
import vkc.view.bean.NewProjectStepInfo;
import vkc.view.bean.ProjectTemplateInfo;
import vkc.view.form.DynaForm;

public class CreateProjectForm extends DynaForm {

	public final static int ACTION_CREATE      = 1;
	public final static int ACTION_CANCEL      = 2;
	public final static int ACTION_INIT        = 3;
	public final static int ACTION_NEWSTEP     = 4;
	public final static int ACTION_DELETESTEPS = 5;

	public final static Integer USENOTEMPLATE_ID = new Integer(0);

	public final static String 	PERMISSIONS_COPY_FROM_TEMPLATE	= "0";
	public final static String	PERMISSIONS_COPY_FROM_TARGET	= "1";
	public final static String	PERMISSIONS_COPY_FROM_DEFAULT	= "2";

	private String 		name				= "";
	private String		description			= "";
	private String		keywords			= "";
	private List	    projectSteps 		= new ArrayList();
	private Integer		parentCategoryId	= new Integer(1);
	private ArrayList	templateInfos		= new ArrayList();
	private Integer		templateIdSelect    = null;
	private String		permissionsSettings = PERMISSIONS_COPY_FROM_TEMPLATE;
	private Integer     sourcePageId 		= PageId.CATEGORY_VIEW;
	private Integer 	targetId 			= null;
	private Integer 	subTargetId 		= null;
	private Integer 	projectId 			= null;

	public String getName() {
		return name;
	}

	public void setName(String string) {
		name = StringUtils.normalize( string );
	}

	public List getProjectSteps() {
		return projectSteps;
	}

    public NewProjectStepInfo getProjectStep(int index) {

        if ( index >= projectSteps.size() ) { // Array vergrössern

            for ( int i=projectSteps.size(); i<=index ; i++ ) {
                projectSteps.add( new NewProjectStepInfo() );
            }
        }

        return (NewProjectStepInfo)projectSteps.get( index );
    }

	public void reset( ActionMapping mapping, HttpServletRequest request ) {

		super.reset( mapping, request );

		name				= "";
		description			= "";
		keywords			= "";
		projectSteps 		= new ArrayList();
		parentCategoryId	= new Integer(1);
		templateInfos		= null;
		templateIdSelect    = null;
		permissionsSettings = PERMISSIONS_COPY_FROM_TEMPLATE;
		sourcePageId 		= PageId.CATEGORY_VIEW;
		targetId 			= null;
		subTargetId 		= null;
		projectId 			= null;
	}

	public ActionErrors validate( ActionMapping mapping, HttpServletRequest request )
	{
		ActionErrors errors = new ActionErrors();

		try {

			if ( request.getParameter( "action.create" ) !=null ) {

				if ( getName().length() == 0 ) {
					errors.add( "name", new ActionError( "error.projectmgmt.name" ) );
				}

				VKCCategory targetCategory = VKCCategorySerializer.retrieveCategory( getParentCategoryId() );
				if ( CategoryUtils.isContained( getName(), targetCategory.getSubCategories(  ) ) ) {
					errors.add( "name", new ActionError( "error.category.name.violation" ) );
				}

				if ( CreateProjectForm.PERMISSIONS_COPY_FROM_TEMPLATE.equals( getPermissionsSettings() ) ) {
					if ( getTemplateIdSelect().intValue() == 0 ) {
						// Übernahme der ACL nicht möglich da keine Vorlage gewählt
						errors.add( "permissionsSettings", new ActionError( "error.category.permission.selection" ) );
					}
				}

				// ProjectSteps durchiterieren und alles überprüfen

				for( int i = 0; i < projectSteps.size(); i++ ) {

					NewProjectStepInfo step = (NewProjectStepInfo)projectSteps.get(i);
					
					Date sd = DateUtils.parseDate( step.getStartDate() );
					Date ed = DateUtils.parseDate( step.getEndDate() );

					if ( isEmpty( step.getActivity() ) ) {
						errors.add( "steps", new ActionError ("error.projectmgmt.steps.noactivity", String.valueOf(i+1) ) );
					} else if ( !isLengthValid( step.getActivity(), "project.steps" ) ) {
						errors.add( "steps", new ActionError( "error.projectmgmt.steps.activity.length" ,
															 String.valueOf( i + 1 ),
															 InputFieldConstraints.getMaxLength("project.steps") ) );
					}
					
					if ( isEmpty( step.getStartDate() ) ) {
						errors.add( "steps", new ActionError ( "error.projectmgmt.steps.missing.startdate", String.valueOf( i + 1 ) ) );
					} else if ( !isParsableDate( step.getStartDate() ) ) {
						errors.add( "steps", new ActionError ( "error.projectmgmt.steps.invalid.startdate", String.valueOf( i + 1 ) ) );
					}

					if ( isEmpty( step.getEndDate() ) ) {
						errors.add( "steps", new ActionError ( "error.projectmgmt.steps.missing.enddate", String.valueOf( i + 1 ) ) );
					} else if ( !isParsableDate( step.getEndDate() ) ) {
						errors.add( "steps", new ActionError ( "error.projectmgmt.steps.invalid.enddate", String.valueOf( i + 1 ) ) );
					}

					if ( sd != null && ed != null && ed.before( sd ) ) {
						errors.add( "steps", new ActionError( "error.projectmgmt.steps.date.range", String.valueOf( i + 1 ) ) );
					}
				}
			}

		} catch (Exception e) {
			VKCLogManager.errorLog( getClass().getName(), "1", "", e );
			errors.add( "error", new ActionError( "error.general", e.getMessage() ) );
		}

		return errors;
	}

	public Integer getParentCategoryId() {
		return parentCategoryId;
	}

	public void setParentCategoryId(Integer integer) {
		parentCategoryId = integer;
	}

	public Integer getTemplateIdSelect() {
		return templateIdSelect;
	}

	public void setTemplateIdSelect(Integer integer) {
		templateIdSelect = integer;
	}

	public ArrayList getTemplateInfos() throws DBException {
		
		if ( templateInfos==null ) {

			templateInfos = new ArrayList();
			if ( getUser()==null ) {
				return templateInfos;
			}

			ProjectTemplateInfo ptiEmpty = new ProjectTemplateInfo();
			ptiEmpty.setDescription( getResources().getMessage(getLocale(),"vkc.projectmgmt.usenotemplate"));
			ptiEmpty.setTemplateId(USENOTEMPLATE_ID);
			templateInfos.add(0, ptiEmpty);

			// TemplateRootCategory aus den Sysparameters holen
			
			Integer rootId = WebShare.getCategorySettings().getProjectManagementTemplateId();

			VKCCategory templateRootCategory = rootId.intValue()>0 
				? VKCCategorySerializer.retrieveCategory(rootId)
				: null;
				
			if ( templateRootCategory !=null ) {

				// TemplateCategories aufbauen
				List templateCategories = templateRootCategory.getAccessibleSubCategories( getUser() );
				for ( Iterator iter = templateCategories.iterator() ; iter.hasNext() ; ) {

					VKCSubCategory subCat = (VKCSubCategory)iter.next();

					ProjectTemplateInfo pti = new ProjectTemplateInfo();
					pti.setDescription( subCat.getName() );
					pti.setTemplateId( subCat.getSubCategoryId() );
					templateInfos.add(pti);
				}
			}
		}
		return templateInfos;
	}

	public void setTemplateInfos(ArrayList list) {
		templateInfos = list;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String string) {
		description = string;
	}

	public String getKeywords() {
		return keywords;
	}

	public void setKeywords(String string) {
		keywords = StringUtils.normalize( string );
	}

	public String getPermissionsSettings() throws DBException {
		
		if ( getTemplateInfos().size()==0 ) {
			permissionsSettings = PERMISSIONS_COPY_FROM_TARGET;
		}
		return permissionsSettings;
	}

	public void setPermissionsSettings(String string) {
		permissionsSettings = StringUtils.normalize( string );
	}
	
	public List getCatProjectSteps() {

		List list = new ArrayList();

		for( int i = 0; projectSteps!=null && i < projectSteps.size(); i++ ) {
			NewProjectStepInfo info = (NewProjectStepInfo)projectSteps.get(i);
            VKCCatProjectStep step = info.toVKCCatProjectStep();
            step.setStep( new Integer( i+1 ) ); 
			list.add( step );
		}
		
		return list;
	}

	public Integer getProjectId() {
		return projectId;
	}

	public Integer getSourcePageId() {
		return sourcePageId;
	}

	public Integer getSubTargetId() {
		return subTargetId;
	}

	public Integer getTargetId() {
		return targetId;
	}

	public void setProjectId( Integer integer ) {
		projectId = integer;
	}

	public void setSourcePageId( Integer integer ) {
		sourcePageId = integer;
	}

	public void setSubTargetId( Integer integer ) {
		subTargetId = integer;
	}

	public void setTargetId( Integer integer ) {
		targetId = integer;
	}
	
	public boolean isCreateNewProjectTabAction() {
		Integer rootId = WebShare.getCategorySettings().getProjectManagementRootId();
		boolean b1 = getSourcePageId().equals( PageId.PROJECT_VIEW );
		boolean b2 = getSourcePageId().equals( PageId.FUNCTIONAL_VIEW );
		boolean b3 = getParentCategoryId().equals( rootId );
		return ( b1 || b2 ) && b3;
	}
}
