/*
 * $Id: TabViewForm.java,v 1.1 2006/10/04 03:15:03 marbobo Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 * $Log: TabViewForm.java,v $
 * Revision 1.1  2006/10/04 03:15:03  marbobo
 * + Vollständige Unterstützung für Templates implementiert
 * + Alles von Virtoweb auf ProCoBa umgestellt
 *
 * Revision 1.31  2006/09/17 21:19:01  marbobo
 * + virtowebView-Einträge und Methoden wegen Migration entfernt (nicht mehr nötig)
 *
 * Revision 1.30  2006/07/05 21:00:07  marbobo
 * + History-Funktionalität für Projekt- und Funktionssicht-Tabs implementiert
 *
 * Revision 1.29  2006/07/03 23:46:31  marbobo
 * + Neu implementierung der Projekt- und Funktionssicht-Tabs
 *
 * Revision 1.28  2006/05/31 13:58:40  marbobo
 * + Bugfix
 *
 * Revision 1.27  2006/05/12 22:14:48  marbobo
 * + Administrationssicht implementiert
 *
 * Revision 1.26  2006/05/12 15:57:23  marbobo
 * + Profil wird jetzt als Registerkarte dargestellt (wegen Vereinheitlichung)
 *
 * Revision 1.25  2006/05/11 20:25:38  marbobo
 * + Zuletzt besuchte Kategorie-ID, Projekte-ID und Funktionen-ID werden nun gespeichert und beim Sichtenwechsel wiederhergestellt
 *
 * Revision 1.24  2006/03/16 22:42:43  marbobo
 * + Layout-Anpassungen
 *
 * Revision 1.23  2006/03/09 17:17:36  marbobo
 * + Layout-Anpassungen
 *
 * Revision 1.22  2006/03/09 01:29:27  marbobo
 * + getRootCategoryLink()
 *
 * Revision 1.21  2006/02/27 16:15:48  marbobo
 * + Systemsichten hinzugefügt
 * + SysLinks angepasst
 * + Benutzer können falls gewünscht Dokumentqueries anlegen
 *
 * Revision 1.20  2005/02/16 16:32:58  jonyp
 * put creator/created into tabinfo
 *
 * Revision 1.19  2004/08/04 23:24:01  marbobo
 * + Status auf Flag umgestellt
 *
 * Revision 1.18  2004/07/20 09:02:07  jonyp
 * added copyright info + cvs log
 *
 *
 */

package vkc.procoba;

import org.apache.struts.action.ActionMapping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import vkc.db.entities.VKCCategory;
import vkc.db.entities.VKCUserFunctionalHistory;
import vkc.db.entities.VKCUserProjectHistory;
import vkc.db.serializer.VKCAclSerializer;
import vkc.db.serializer.VKCTabViewSerializer;
import vkc.db.serializer.VKCUserFunctionalHistorySerializer;
import vkc.db.serializer.VKCUserProjectHistorySerializer;
import vkc.exception.DBException;
import vkc.help.form.HelpViewForm;
import vkc.view.PageId;
import vkc.view.TabId;
import vkc.view.WebShare;
import vkc.view.bean.ProjectInfo;
import vkc.view.form.BasicActionForm;
import vkc.view.form.SysLinkForm;
import vkc.procoba.function.FunctionalViewInfo;
import vkc.procoba.function.FunctionalViewUtils;
import vkc.security.PermissionManager;
import vkc.security.VKCAcl;

public class TabViewForm extends BasicActionForm {
	public static final int NUM_ADDITIONAL_TABS = 2;

	protected boolean newProjectTabSelected = false;
	protected boolean reloadMainview = false;

	protected Integer lastCategoryId = new Integer(VKCCategory.ROOT_CATEGORY_ID);
	protected Integer lastFunctionalId = new Integer(-1);
	protected Integer lastProjectId = new Integer(-1);
	protected Integer selectedAddTabId = null;
	protected Integer selectedTabId = WebShare.getCategorySettings().getProjectManagementRootId();
	protected Integer selectedViewId = PageId.PROJECT_VIEW;
	protected Integer viewId = null;

	protected List additionalTabInfos = new ArrayList();
	protected List systemTabInfos = new ArrayList();
	protected List tabInfos = new ArrayList();
	protected List mostRecentProjects = null;
	protected List mostRecentFunctionals = null;

	public void reset(ActionMapping mapping, HttpServletRequest request) {
		super.reset(mapping, request);

		newProjectTabSelected = false;
		reloadMainview = false;

		lastCategoryId = new Integer(VKCCategory.ROOT_CATEGORY_ID);
		lastFunctionalId = new Integer(-1);
		lastProjectId = new Integer(-1);
		selectedAddTabId = new Integer(-1);
		selectedTabId = WebShare.getCategorySettings().getProjectManagementRootId();
		selectedViewId = PageId.PROJECT_VIEW;
		viewId = PageId.PROJECT_VIEW;

		additionalTabInfos = new ArrayList();
		systemTabInfos = new ArrayList();
		tabInfos = new ArrayList();
	}

	public Integer getViewId() {
		return viewId;
	}

	public void setViewId(Integer integer) {
		viewId = integer;
		additionalTabInfos = new ArrayList();
		systemTabInfos = new ArrayList();
		tabInfos = new ArrayList();
	}

	public Integer getSelectedTabId() {
		return selectedTabId;
	}

	public void setSelectedTabId(Integer integer) {
		selectedTabId = integer;
	}

	public boolean isProjectViewSelected() {
		return PageId.PROJECT_VIEW.equals(getViewId());
	}

	public boolean isFunctionalViewSelected() {
		return PageId.FUNCTIONAL_VIEW.equals(getViewId());
	}

	public List getMostRecentTabInfos() throws DBException {
		if (getUser() == null) {
			return new ArrayList();
		}
		
		List mostRecentTabInfos = new ArrayList();
		
		if (isFunctionalViewSelected()) {
			for (int i = 0; i < getMostRecentFunctionals().size(); i++) {
				VKCUserFunctionalHistory ufh = (VKCUserFunctionalHistory)getMostRecentFunctionals().get(i);
				
				for (int j = 0; j < getTabInfos().size(); j++) {
					TabInfo tabInfo = (TabInfo)getTabInfos().get(j);
					
					if (tabInfo.getTabId().equals(ufh.getFunctionalId())) {
						mostRecentTabInfos.add(tabInfo);
						break;
					}
				}
			}
		} else if (isProjectViewSelected()) {
			for (int i = 0; i < getMostRecentProjects().size(); i++) {
				VKCUserProjectHistory uph = (VKCUserProjectHistory)getMostRecentProjects().get(i);
				
				for (int j = 0; j < getTabInfos().size(); j++) {
					TabInfo tabInfo = (TabInfo)getTabInfos().get(j);
					
					if (tabInfo.getTabId().equals(uph.getProjectId())) {
						mostRecentTabInfos.add(tabInfo);
						break;
					}
				}
			}
		}

		return mostRecentTabInfos;
	}

	public List getTabInfos() throws DBException {
		if (getUser() == null) {
			return new ArrayList();
		}

		if (tabInfos == null || tabInfos.isEmpty()) {
			tabInfos = new ArrayList();

			if (isProjectViewSelected()) {
				List projectInfos = getUser().getProjectInfos();

				for (Iterator iter = projectInfos.iterator(); iter.hasNext();) {
					ProjectInfo info = (ProjectInfo)iter.next();

					TabInfo tabInfo = new TabInfo();
					tabInfo.setTabId(info.getId());
					tabInfo.setTabName(info.getName());
					tabInfo.setTabDescription(info.getDescription());
					tabInfo.setTabLink("/procobaTab.do?viewId=" + PageId.PROJECT_VIEW 
									+ "&selectedTabId=" + info.getId() 
									+ "&selectedViewId=" + PageId.PROJECT_VIEW
									+ "&reloadMainview=true"
									+ "&lastCategoryId=" + getLastCategoryId()
									+ "&lastFunctionalId=" + getLastFunctionalId()
									+ "&lastProjectId=" + info.getId());
					tabInfo.setTabFlag(info.getProjectflag());
					tabInfo.setTabStatus(info.getProjectstatus());
					
					String s = getResources().getMessage(getLocale(), "project.label.flag") + ": ";
					
					if (tabInfo.getTabFlag().equals(VKCCategory.FLAG_CLOSED)) {
						s += getResources().getMessage(getLocale(), "project.label.flag.closed");
					} else if (tabInfo.getTabFlag().equals(VKCCategory.FLAG_CREATED)) {
						s += getResources().getMessage(getLocale(), "project.label.flag.created");
					} else if (tabInfo.getTabFlag().equals(VKCCategory.FLAG_ACTIVE)) {
						s += getResources().getMessage(getLocale(), "project.label.flag.active");
					} else if (tabInfo.getTabFlag().equals(VKCCategory.FLAG_ARCHIVED)) {
						s += getResources().getMessage(getLocale(), "project.label.flag.archived");
					} else if (tabInfo.getTabFlag().equals(VKCCategory.FLAG_DELETED)) {
						s += getResources().getMessage(getLocale(), "project.label.flag.deleted");
					}
					
					tabInfo.setTabFlagLabel(s);
					
					String creator = getResources().getMessage(getLocale(), "project.label.creator") + ": ";
					tabInfo.setTabCreator(creator);
					
					String created = getResources().getMessage(getLocale(), "project.label.created") + ": ";
					tabInfo.setTabCreated(created);
					
					tabInfos.add(tabInfo);
				}
			} else if (isFunctionalViewSelected()) {
				List functionInfos = FunctionalViewUtils.getFunctionalViewInfos(getUser());

				for (Iterator iter = functionInfos.iterator(); iter.hasNext();) {
					FunctionalViewInfo info = (FunctionalViewInfo)iter.next();

					TabInfo tabInfo = new TabInfo();
					tabInfo.setTabName(info.getName());
					tabInfo.setTabId(info.getCategoryId());
					tabInfo.setTabLink("/procobaTab.do?viewId=" + PageId.FUNCTIONAL_VIEW 
									+ "&selectedTabId=" + info.getCategoryId() 
									+ "&selectedViewId=" + PageId.FUNCTIONAL_VIEW
									+ "&reloadMainview=true"
									+ "&lastCategoryId=" + getLastCategoryId()
									+ "&lastFunctionalId=" + getLastFunctionalId()
									+ "&lastProjectId=" + getLastProjectId());

					tabInfos.add(tabInfo);
				}
			}
		}

		return tabInfos;
	}

	public void setTabInfos(List list) {
		tabInfos = list != null ? list : new ArrayList();
	}

	protected int getSelectedTabIndex() throws DBException {
		for (int i = 0; i < getTabInfos().size(); i++) {
			TabInfo info = (TabInfo)getTabInfos().get(i);
			
			if (info.getTabId().intValue() == getSelectedTabId().intValue()) {
				return i;
			}
		}
		
		return -1;
	}

	public TabInfo getFirstTabInfo() throws DBException {
		if (getTabInfos().size() > 0) {
			return (TabInfo)getTabInfos().get(0);
		} 

		return null;
	}

	public TabInfo getLastTabInfo() throws DBException {
		if (getTabInfos().size() > 0) {
			return (TabInfo)getTabInfos().get(getTabInfos().size() - 1);
		} 

		return null;
	}

	public TabInfo getFirstLeftInvisibleTabInfo() throws DBException {
		if (getHasMoreLeftSideTabs()) {
			return (TabInfo)getTabInfos().get(getSelectedTabIndex() - NUM_ADDITIONAL_TABS + 1);
		} 

		return null;
	}

	public TabInfo getFirstRightInvisibleTabInfo() throws DBException {
		if (getHasMoreRightSideTabs()) {
			return (TabInfo)getTabInfos().get(getSelectedTabIndex() + NUM_ADDITIONAL_TABS - 1);
		} 

		return null;
	}

	public boolean getHasMoreLeftSideTabs() throws DBException {
		int tabIndex = getSelectedTabIndex();

		if (tabIndex < 0) {
			return false;
		} 

		return tabIndex - NUM_ADDITIONAL_TABS > 0;
	}

	public boolean getHasMoreRightSideTabs() throws DBException {
		int tabIndex = getSelectedTabIndex();

		if (tabIndex < 0) {
			return false;
		} 

		return getTabInfos().size() > tabIndex + (NUM_ADDITIONAL_TABS + 1) ;
	}

	public List getVisibleTabInfos() throws DBException {
		List tabInfos = getTabInfos();
		
		if (tabInfos.size() <= (NUM_ADDITIONAL_TABS * 2 + 1)) {
			return tabInfos;
		}

		List visibleTabInfos = new ArrayList();

		int selectedIndex = getSelectedTabIndex();
		int startIndex = selectedIndex - NUM_ADDITIONAL_TABS;
		int endIndex   = selectedIndex + NUM_ADDITIONAL_TABS;

		if (startIndex < 0) {
			endIndex -= startIndex;
			startIndex = 0;
		}

		if (endIndex >= tabInfos.size()) {
			endIndex = tabInfos.size() - 1;
		}
		
		for (int i = startIndex; i <= endIndex; i++) {
			visibleTabInfos.add(tabInfos.get(i));
		}

		return visibleTabInfos;
	}

	public HashMap getRootCategoryLinkParams() {
		HashMap params = new HashMap();
		params.put("linkType", SysLinkForm.CATEGORY_LINK);
		params.put("objectId", new Integer(VKCCategory.ROOT_CATEGORY_ID));
		
		return params;
	}
	
	public String getRootCategoryLink() {
		return SysLinkForm.getCategorySysLink(new Integer(VKCCategory.ROOT_CATEGORY_ID), null);
	}
	
	public String getCreateNewProjectTabLink() {
		Integer rootId = WebShare.getCategorySettings().getProjectManagementRootId();
		
		return "/createCategory.do?" +
			   "sourcePageId=" +  getViewId() +
			   "&targetId=" + rootId +
			   "&subTargetId=" + rootId +
			   "&parentCategoryId=" + rootId +
			   "&validate=false" + 
			   "&copyParentAcl=true";
	}
	
	public TabInfo getCreateNewProjectTabInfo() {
		Integer rootId = WebShare.getCategorySettings().getProjectManagementRootId();
		TabInfo tabInfo = new TabInfo();
		tabInfo.setTabName("");
		tabInfo.setTabId(rootId);
		tabInfo.setTabLink("/procobaTab.do?viewId=" + getViewId() 
						+ "&selectedTabId=" + rootId 
						+ "&selectedViewId=" + getViewId()
						+ "&reloadMainview=true&newProjectTabSelected=true&ignoreTabviewLoad=true"
						+ "&lastCategoryId=" + getLastCategoryId()
						+ "&lastFunctionalId=" + getLastFunctionalId()
						+ "&lastProjectId=" + getLastProjectId());

		return tabInfo;
	}
	
	public boolean isCreateNewProjectTabSelected() {
		Integer rootId = WebShare.getCategorySettings().getProjectManagementRootId();

		if (getSelectedTabId().equals(rootId) && isNewProjectTabSelected()) {
			return true;
		} 
		
		return false;
	}

	public Integer getSelectedViewId() {
		return selectedViewId;
	}

	public void setSelectedViewId(Integer integer) {
		selectedViewId = integer;
	}
	
	/**
	 * asks, if a user is allowed to create new projects 
	 * as project leader you must have permissions "C" at least
	 * in the projectRootCategory
	 * @return true => yes, you are allowed  no => no, you aren't
	 * @throws DBException
	 */
	public boolean getAllowCreateNewProjectTab() throws DBException {
		Integer projectManagementRootId = WebShare.getCategorySettings().getProjectManagementRootId();
		VKCAcl acl = VKCAclSerializer.getAclByCategoryId(projectManagementRootId);

		if (PermissionManager.hasPermission(acl, getUser(), 'C') == true) {
            return true;    
		} 

		return false; 
	}

	public boolean isReloadMainview() {
		return reloadMainview;
	}

	public void setReloadMainview(boolean reloadMainview) {
		this.reloadMainview = reloadMainview;
	}

	public List getAdditionalTabInfos() {
		if (getUser() == null) {
			return new ArrayList();
		}

		if (additionalTabInfos == null || additionalTabInfos.isEmpty()) {
			HashMap tabViews = VKCTabViewSerializer.getTabViews(getLocale(), getResources());
			additionalTabInfos = new ArrayList();
			
			// Profil-Tab
			vkc.view.bean.TabInfo tabInfo = (vkc.view.bean.TabInfo)tabViews.get(new Integer(TabId.PROFILE_TAB));
			
			if (tabInfo.isEnabled()) {
				if (!getUser().isGuestUser()) {
					tabInfo.setTabLink("/userProfile.do?initialize=true");
					additionalTabInfos.add(tabInfo);
				}
			}

			// Help-Tab
			tabInfo = (vkc.view.bean.TabInfo)tabViews.get(new Integer(TabId.HELP_TAB));
			
			if (tabInfo.isEnabled()) {
				tabInfo.setTabLink("/helpView.do?viewId=" + HelpViewForm.PROCOBA_VIEW);
				tabInfo.setTabDescription(getResources().getMessage(getLocale(), "vkc.open.help"));
				additionalTabInfos.add(tabInfo);
			}
		}
		
		return additionalTabInfos;
	}

	public void setAdditionalTabInfos(List additionalTabInfos) {
		this.additionalTabInfos = additionalTabInfos != null ? additionalTabInfos : new ArrayList();
	}

	public Integer getSelectedAddTabId() {
		return selectedAddTabId;
	}

	public void setSelectedAddTabId(Integer selectedAddTabId) {
		this.selectedAddTabId = selectedAddTabId;
	}

	public List getSystemTabInfos() {
		if (getUser() == null) {
			return new ArrayList();
		}

		if (systemTabInfos == null || systemTabInfos.isEmpty()) {
			systemTabInfos = new ArrayList();
			vkc.view.bean.TabInfo tabInfo = null;
			
			if (getUser().isAllowManageSystemViewType()) {
				tabInfo = new vkc.view.bean.TabInfo();
				tabInfo.setTabId(PageId.CATEGORY_VIEW);
				tabInfo.setTabName(getResources().getMessage(getLocale(), "vkc.systemviewtype.categoryview"));
				tabInfo.setTabDescription(getResources().getMessage(getLocale(), "vkc.systemviewtype.categoryview.switch"));
				systemTabInfos.add(tabInfo);
			}

			tabInfo = new vkc.view.bean.TabInfo();
			tabInfo.setTabId(PageId.PROJECT_VIEW);
			tabInfo.setTabName(getResources().getMessage(getLocale(), "projectview"));
			tabInfo.setTabDescription(getResources().getMessage(getLocale(), "projectview.switch"));
			systemTabInfos.add(tabInfo);

			tabInfo = new vkc.view.bean.TabInfo();
			tabInfo.setTabId(PageId.FUNCTIONAL_VIEW);
			tabInfo.setTabName(getResources().getMessage(getLocale(), "functionview"));
			tabInfo.setTabDescription(getResources().getMessage(getLocale(), "functionview.switch"));
			systemTabInfos.add(tabInfo);

			if (getUser().hasAdminPrivileges() || getUser().isDedicatedAdmin()) {
				tabInfo = new vkc.view.bean.TabInfo();
				tabInfo.setTabId(PageId.ADMINISTRATION_VIEW);
				tabInfo.setTabName(getResources().getMessage(getLocale(), "vkc.systemviewtype.adminview"));
				tabInfo.setTabDescription(getResources().getMessage(getLocale(), "vkc.systemviewtype.adminview.switch"));
				systemTabInfos.add(tabInfo);
			}
		}
		
		return systemTabInfos;
	}

	public void setSystemTabInfos(List systemTabInfos) {
		this.systemTabInfos = systemTabInfos != null ? systemTabInfos : new ArrayList();
	}

	public Integer getLastFunctionalId() {
		return lastFunctionalId;
	}

	public void setLastFunctionalId(Integer lastFunctionalId) {
		this.lastFunctionalId = lastFunctionalId;
	}

	public Integer getLastProjectId() {
		return lastProjectId;
	}

	public void setLastProjectId(Integer lastProjectId) {
		this.lastProjectId = lastProjectId;
	}

	public Integer getLastCategoryId() {
		return lastCategoryId;
	}

	public void setLastCategoryId(Integer lastCategoryId) {
		this.lastCategoryId = lastCategoryId;
	}

	public boolean isNewProjectTabSelected() {
		return newProjectTabSelected;
	}

	public void setNewProjectTabSelected(boolean newProjectTabSelected) {
		this.newProjectTabSelected = newProjectTabSelected;
	}

	public List getMostRecentFunctionals() throws DBException {
		if (mostRecentFunctionals == null) {
			mostRecentFunctionals = VKCUserFunctionalHistorySerializer.retrieveHistoryInfos(getUser().getUserId(), 5);
		}
		
		return mostRecentFunctionals;
	}

	public List getMostRecentProjects() throws DBException {
		if (mostRecentProjects == null) {
			mostRecentProjects = VKCUserProjectHistorySerializer.retrieveHistoryInfos(getUser().getUserId(), 5);
		}
		
		return mostRecentProjects;
	}
}