// Copyright 2008 ProjectWizards GmbH. All rights reserved.

//console.log("ResourcesViewController");

var ResourcesViewController = ViewController.extend({
	constructor: function(container, moc, environment, styleList, columns, initialSortDescriptors, actionMethods, addResourceButton, addResourceGroupButton, printPageURL, splitViewState, isBeingExportedForQuicklook){
		this.base(moc);
		this.initialSortDescriptors = initialSortDescriptors;
		this.printPageURL = printPageURL;
		this.addResourceButton = PWUtils.makeMultiStateButton(addResourceButton);
		this.addResourceGroupButton = PWUtils.makeMultiStateButton(addResourceGroupButton);
		this.actionMethods = actionMethods;
		this.container = container;
		this.moc = moc;
		this.environment = environment;
		this.styleList = styleList;
		this.columns = columns;
		this.splitView = new SplitView(this.container, 200, 9, 6, 110, 300, true);
		var groupsContainer = DIV({'class':'recourcesGroupsContainer'});
		var resourcesContainer = DIV({'class':'recourcesContainer'});
		this.splitView.firstDiv.appendChild(groupsContainer);
		this.splitView.secondDiv.appendChild(resourcesContainer);
		this.splitView.setDelegate(this);

		// Resources
		this.resourcesOutlineController = new OutlineController(environment);
		this.resourcesOutlineController.setSortDescriptors(this.initialSortDescriptors);
		this.resourcesOutlineView = new OutlineView(resourcesContainer, this.resourcesOutlineController, 20, null, true, environment, false, this);
		this.isBeingExportedForQuicklook = isBeingExportedForQuicklook;
		if(this.isBeingExportedForQuicklook)
			this.resourcesOutlineView.setEnableDrags(false);
		this.resourcesOutlineView.setColumnsAndOutlineColumnKey(columns, 'title');
		this.resourcesOutlineView.setHeaderHeight(36);
		this.resourcesOutlineView.setYScrollBarType("auto");
		
		// Resource Groups
		this.groupsOutlineController = new OutlineController(environment);
		this.groupsOutlineController.setSortDescriptors([{key:'title', ascending: true}]);
		this.groupsOutlineController.setChildrenKey('resourceGroups');
		this.groupsOutlineView = new OutlineView(groupsContainer, this.groupsOutlineController, 20, null, true, environment, false, this);
		if(this.isBeingExportedForQuicklook)
			this.groupsOutlineView.setEnableDrags(false);
		this.groupsOutlineView.setSingleSelection(true);
		this.groupsOutlineView.setShowsHeader(false);
		this.groupsOutlineView.setAlternateRows(false);
		this.groupsOutlineView.setColumnsAndOutlineColumnKey([new TableColumn('title', 'Title', '', 230, 1, 'l', 'l')], 'title');

		this.groupsOutlineView.setYScrollBarType("auto");
		this.groupsOutlineView.setXScrollBarType("hidden");


//		this.groupsOutlineView.setEnableScrollBars(false);
		this.groupsOutlineView.outlineColumnPadding = 5;
		this.setProjects(this.projectsInManagedObjectContext());
		this.groupsOutlineView.refresh();
		this.groupsOutlineView.selectNextRow();
		this.updateControlsEnabledStatus();
		NotificationCenter.defaultNotificationCenter().addObserverForMessage(this, WRLAjaxContextChangedByServerNotification, "managedObjectContextChangedByServer");	

		this.setSplitViewState(splitViewState);
	},
	
	updateTooltip: function(){
		Tooltip.attach(this.groupsButton, this.splitView.isFirstViewVisible() ? this.hideGroupsText : this.showGroupsText);
	},

	setGroupButtonShowHideText: function(button, showText, hideText){
		this.groupsButton = button;
		this.showGroupsText = showText;
		this.hideGroupsText = hideText;
		this.updateTooltip();	
	},

	canAddResourceGroups: function(){
		return this.groupsOutlineController.selectedObjects.length == 1;
	},

	canAddResources: function(){
		return this.groupsOutlineController.selectedObjects.length == 1;		
	},

	updateControlsEnabledStatus: function(){
		if(this.addResourceButton)
			this.addResourceButton.setEnabled( this.canAddResources() );
		if(this.addResourceGroupButton)
			this.addResourceGroupButton.setEnabled( this.canAddResourceGroups() );
	},

	managedObjectContextChangedByServer: function(msg, userInfo){
		if(userInfo.context == this.moc){
			if(userInfo.result && (userInfo.result.deleted.length || userInfo.result.updated.length)) {
				this.refresh();
			}
		}
	},

	selectAll: function() {
		if(this.focusedOutlineView) {
			var flatObjects = this.focusedOutlineView.controller.getFlatObjects();
			if(flatObjects.length) {
				this.focusedOutlineView.controller.setSelectedObjects(flatObjects);	
				this.refresh();
			}
		}
	},

	refresh: function() {
		this.setProjects(this.projectsInManagedObjectContext());

        if(this.didSelectFirstGroupItem != true && this.groupsOutlineView.rows().length > 1){
            this.didSelectFirstGroupItem = true;
            this.groupsOutlineView.selectRows([this.groupsOutlineView.rowAtIndex(0)]);
        }

		this.setResources(this.visibleResources());
		this.updateControlsEnabledStatus();		
	},

	projectsInManagedObjectContext: function() {
		var result = [];
		for(var key in this.moc.registeredObjects){
			var object = this.moc.registeredObjects[key]; 
			if(object.className() == "MEProject")
				result.push(object);
		}
		if(result.length > 1)
			result.push(new AllProjectsItem(this.moc, this.environment));
		return result;		
	},

	mainProject: function(){
		var projects = [];
		var projectLinks = [];
		for(var key in this.moc.registeredObjects){
			var object = this.moc.registeredObjects[key]; 
			if(object.className() == "MEProject")
				projects.push(object);
			else if(object.className() == "MEProjectLink")
				projectLinks.push(object);
		}
		projectLinks.each(function(projectLink){
			projects = projects.without(projectLink.valueForKey("targetProject"));
		});
		return projects[0];
	},

	setResources: function(resources) {
		this.resourcesOutlineController.setRootObjects(resources);
		if(this.isVisible())
			this.resourcesOutlineView.refresh();
	},

	setProjects: function(projects) {
		this.groupsOutlineController.setRootObjects(projects);
		if(this.isVisible())
			this.groupsOutlineView.refresh();
	},

	isVisible: function(){
		var style = PWUtils.effectiveStyle(this.container);
		return style.display != "none";
	},

	setIsVisible: function(flag){
		this.groupsOutlineView.setEnableDrops(flag);
		this.container.style.display = flag ? "block" : "none";
		if(flag){
			this.resourcesOutlineView.refresh();
			this.groupsOutlineView.refresh();
		}
	},
	
	addResource: function() {
		if(this.groupsOutlineController.selectedObjects.length){
			var group = this.groupsOutlineController.selectedObjects[0];
			var project;
			if(group.className() != "MEResourceGroup"){
				if(group.className() == "MEProject")
					project = group;
				else 
					group = project = this.mainProject();	// AllProjectsItem
			}else
				project = group.valueForKey("project");
			var request = {project:project.uri()};
			if(project != group)
				request.group = group.uri();
			var objectID = this.actionMethods.addResource(request);
			this.moc.synchronize();	
			var object = this.moc.registeredObjectWithURIString(objectID);
			if(object){
				this.setResources(this.visibleResources());
				this.resourcesOutlineController.setSelectedObjectIDs([objectID]);
				this.focusOutlineView(this.resourcesOutlineView);
				this.resourcesOutlineView.refresh();
				var me = this;
				(function() { me.resourcesOutlineView.editSelectedRow() }).delay(0);
			}
		}
	},
	
	addResourceGroup: function() {
		var selectedObjectIDs = this.groupsOutlineController.selectedObjectIDs();
		if(selectedObjectIDs.length){
			var objectID = this.actionMethods.addResourceGroup({selectedObjectIDs:selectedObjectIDs});
			this.moc.synchronize();	
			var object = this.moc.registeredObjectWithURIString(objectID);
			if(object){
				this.groupsOutlineController.setSelectedObjects([object]);
				this.focusOutlineView(this.groupsOutlineView);
				this.groupsOutlineView.refresh();
				var me = this;
				(function() { me.groupsOutlineView.editSelectedRow() }).delay(0);
			}
		}	
	},
	
	toggleGroupView: function() {
		this.splitView.toogleFirstView();
		this.updateTooltip();
	},

	willMoveSplitterAction: function(splitView) {
	
	},

	moveSplitterAction: function(splitView) {
		this.resourcesOutlineView.containerSizeChanged();	
		this.groupsOutlineView.containerSizeChanged();	
	},
	
	splitterChangedAction: function(splitView) {
		this.resourcesOutlineView.containerSizeChanged();
		this.groupsOutlineView.containerSizeChanged();	
		if(!this.splitView.isFirstViewVisible()){
			var groups = this.groupsOutlineController.getFlatObjects();
			if(groups && groups.length){
				this.groupsOutlineController.setSelectedObjects([groups[0]]);
				this.groupsOutlineView.refresh();
				this.outlineDidChangeSelection(this.groupsOutlineView);
				this.focusOutlineView(this.resourcesOutlineView);
			}
		}
	},

	selectedObjects: function(){
		var result = [];
		if(this.focusedOutlineView)
			result = this.focusedOutlineView.controller.selectedObjects;
		return result;
	},

	// ***************  Delegate Methoden der Outline View *****************

	outlineShouldDragRows: function(outline, rows){
		return outline == this.resourcesOutlineView;
	},

	pasteboardContentFromRows: function(outline, rows){
		var result = [];
		for(var i=0; i<rows.length; i++){
			var object = rows[i].object;
			result.push({data:object, type:object.className()});
		}
		return result; 
	},

	outlineValidateDrop: function(outline, location, pasteboard){		
		if(outline == this.groupsOutlineView){
			if(location.row && location.row != OutlineView.MOUSE_IS_NOT_IN_OUTLINE && location.row != OutlineView.MOUSE_IS_NOT_IN_ROW && location.row.object.className() == "MEResourceGroup")
				return {accept:true, area:'middle'};
		}
		return {accept:false};
	},

	outlineAcceptDrop: function(outline, location, pasteboard){
		if(location.row){
			var group = location.row.object;
			for(var i=0; i<pasteboard.length; i++){
				var objectDescription = pasteboard[i];
				var type = objectDescription.type;
				if(objectDescription.type == "MEResource" || objectDescription.type == "MEMasterResource"){
					var resource = objectDescription.data;
					var groups = resource.valueForKey('groups');
					if(!groups)
						groups = [];
					groups.push(group);
					groups = groups.uniq();
					resource.setValueForKey(groups, 'groups');
				}
			}
			this.moc.synchronize();
		}
	},
	
	outlineHeightForRow: function(outline, row){
		return 20;
	},
	
	outlineDidCreateCellInRow: function(outline, cell, row, editMode){
		if(this.resourcesOutlineView == outline && cell.column == outline.outlineColumn){
			var imagePath = this.environment.images.Resource;
			switch(parseInt(row.object.valueForKey("type"))){
				case MEResource.MEResourceType.MEMaterialResource: 
					var imagePath = this.environment.images.MEMaterialResource;
					break;
				case MEResource.MEResourceType.MECompanyResource: 
					var imagePath = this.environment.images.MECompanyResource;
					break;
				case MEResource.MEResourceType.MEEquipmentResource: 
					var imagePath = this.environment.images.MEEquipmentResource;
					break;
			}
			cell.appendChild(IMG({width:15, height:14, src:imagePath, style:"vertical-align:middle; margin-left:"+3+"px; margin-right:4px;"}));
		}else if(this.groupsOutlineView == outline){
			var imagePath = this.environment.images.ViewGroups;
			var width = 19;
			var height = 14;
			if(row.object.className() == "MEProject" || row.object.className() == "AllProjectsItem"){
				imagePath = this.environment.images.MEProject;
				width =15;
				height = 14;
				cell.style.fontWeight='bold';
				cell.style.marginLeft = "9px";
				cell.style.paddingLeft = "9px";
			}
			var resourceGroups = row.object.valueForKey('resourceGroups')
			var hasChilds = resourceGroups && resourceGroups.length;
			cell.appendChild(IMG({width:width, height:height, src:imagePath, style:"vertical-align:middle; margin-left:"+(3+(!hasChilds ? 9 : 0))+"px; margin-right:4px;"}));
		}
	},

	outlineDidCreateRow: function(outline, row){
		row.originalColor = "#000000";
	},

	outlineDidCreateRows: function(outline, rows){

	},

	outlineRowsBecameVisible: function(outline, rows){

	},

	outlineChanged: function(outline, rows){		

	},

	outlineViewDidCreateDisclosureButtonForRow: function(outline, button, row){

	},

	outlineViewShouldHandleClickInRow: function(outline, row){
		return true;
	},

	focusOutlineView: function(outline){
		if(this.focusedOutlineView != outline){
			this.focusedOutlineView = outline;
			this.resourcesOutlineView.setIsFocused(outline == this.resourcesOutlineView);
			this.groupsOutlineView.setIsFocused(outline == this.groupsOutlineView);
		}
	},

	visibleResources: function(){
		var resourcesToShow = [];
		var objects = this.groupsOutlineController.selectedObjects;
		for(var i=0; i<objects.length; i++){
			var object = objects[i];
			var resources = object.valueForKey("resources");
			for(var k=0; k<resources.length; k++){
				var resource = resources[k];
				if(resourcesToShow.indexOf(resource) == -1)
					resourcesToShow.push(resource);
			}
			if(object.className() == "AllProjectsItem")
				break;
		}
		return resourcesToShow;
	},

	outlineDidChangeSelection: function(outline)
	{
		this.focusOutlineView(outline);
		if(outline == this.groupsOutlineView)
			this.setResources(this.visibleResources());
		this.updateControlsEnabledStatus();		
	},

	outlineShouldEditObjectProperty: function(outline, object, key){
		if(object.className() == "MEProject")
			return false;
		this.editedOutlineView = outline;
		var result = eval(this.actionMethods.shouldEditObjectProperty({objectID:object.objectID.uri, key:key}));
		return result;
	},
	
	outlineValidatePropertyOfObject: function(outline, property, object, validationDidEndHandler){
		var propertyName;
		var value;
		for(propertyName in property){
			value = property[propertyName];
			break;
		}
		var result = this.actionMethods.validatePropertyOfObject({propertyName:propertyName, value:value, objectID:object.objectID.uri});
		result = eval("("+result+")");
		if(result.validated){
			var object = this.moc.registeredObjectWithURIString(result.objectID);
			if(object){ 
				var value = object.createValueForPropertyFromJSON(result.propertyName, result.value);
				object.setValueForKey(value, result.propertyName);
				this.moc.synchronize();
				validationDidEndHandler.call(outline, result);
			}
		}
	},
	
	outlineDidFinishEditing: function(outline){
		this.editedOutlineView = null;
	},
	
	
	// ********************* Key handling *********************
	
	moveUp: function(sender, evt) {
		if(this.focusedOutlineView)
			this.focusedOutlineView.selectPreviousRow(false);
		return true;
	},

	moveDown: function(sender, evt) {
		if(this.focusedOutlineView)
			this.focusedOutlineView.selectNextRow(false);
		return true;
	},

	moveLeft: function(sender, evt) {
		if(this.focusedOutlineView && this.focusedOutlineView == this.groupsOutlineView)
			this.focusedOutlineView.setSelectedRowsCollapsed(true);
		return true;
	},

	moveRight: function(sender, evt) {
		if(this.focusedOutlineView && this.focusedOutlineView == this.groupsOutlineView)
			this.focusedOutlineView.setSelectedRowsCollapsed(false);
		return true;
	},

	closeDatePicker: function() {
		if(window["datePickerIsVisible"] && datePickerIsVisible()){
			closeCalendar();
			return true;
		}	
	},

	insertNewline: function(sender, evt){
		if(this.focusedOutlineView && !this.closeDatePicker())
			this.focusedOutlineView.editSelectedRow();
		return true;
	},
	
	insertTab: function(sender, evt){
		if(this.editedOutlineView  && !this.closeDatePicker())
			this.editedOutlineView.editNextProperty();		
		return true;
	},
	
	deleteBackward: function(sender, evt){
		this.deleteSelectedObjects();	
		return true;
	},	

	deleteForward: function(sender, evt){
		this.deleteSelectedObjects();	
		return true;
	},	

	selectedGroupObject: function(){
		var selectedGroups = this.groupsOutlineController.selectedObjects;
		return selectedGroups && selectedGroups.length ? selectedGroups[0] : null;
	},
	
	deleteSelectedObjects: function(){
		var objects = this.selectedObjects();
		if(objects.length){
			var objectIDs = [];
			var objectsToDelete = [];
			objects.each(function(object){
				if(object.uri && object.className() != "MEProject"){
					objectIDs.push(object.uri());
					objectsToDelete.push(object);
				}
			});
			if(objectIDs.length){
				var selectedGroupObject = this.selectedGroupObject();
				if(this.focusedOutlineView == this.resourcesOutlineView && selectedGroupObject && selectedGroupObject.className() != "MEProject"){
					objectsToDelete.each(function(object){
						object.setValueForKey(object.valueForKey("groups").without(selectedGroupObject), 'groups');
					});
				}else
					this.actionMethods.deleteObjects({objectIDs:objectIDs});
				this.moc.synchronize();	
				this.focusedOutlineView.controller.setSelectedObjects([]);
				this.refresh();

			}
		}
	},
	
	canDeleteSelection: function() {
		return this.selectedObjects().length ? true : false;
	},

	
	print: function(){
		var info = {};
		info.environment = this.environment;
		info.outlineSize = {	 width:this.resourcesOutlineView.tableWidth(), height:this.resourcesOutlineView.fullHeight()};
		info.outlineController = this.resourcesOutlineController;
		info.columns = this.columns;
		info.styleList = this.styleList;
		info.moc = this.moc;		
		info.delegate = this;
		window.info = info;
		this.printWindow = window.open(Prototype.Browser.WebKit ? this.printPageURL : '', '','height=600, width=800, resizable=1, scrollbars=1');
		if(!this.printWindow.info)
			this.printWindow.info = info;
		if(window.focus) 
			this.printWindow.focus();				
		if(!Prototype.Browser.WebKit){	
			this.printWindow.location = this.printPageURL;
		}
	},
	
	isEditing: function() {
		return this.resourcesOutlineView.isEditing() || this.groupsOutlineView.isEditing();
	},

	setSplitViewState: function(splitViewState) {
		var splitterPos = parseFloat(eval('('+splitViewState+')'));
		if(splitterPos <= 0)
			this.splitView.hideFirstView();
		else
			this.splitView.showFirstView();	
	},
	
	fetchWorkspace: function() {
		var workspaceData = eval('('+this.actionMethods.getWorkspaceData({})+')');
		this.styleList = eval('('+workspaceData.styleList+')');
		this.columns = eval('('+workspaceData.columns+')');
		if(workspaceData.splitViewState)
			this.setSplitViewState(workspaceData.splitViewState);
		this.resourcesOutlineView.setColumnsAndOutlineColumnKey(this.columns, 'title');
		var projects = this.projectsInManagedObjectContext();
		this.setProjects(projects);
		if(projects.length)
			this.groupsOutlineController.setSelectedObjects([projects[0]]);
		this.setResources(this.visibleResources());
		this.updateControlsEnabledStatus();		
		this.refresh();
	},
	
	workspaceViewName: function() {
		return "resourcesViewController";
	}
	
});
