/**
 * All intellectual property rights in this Software throughout the world belong to UK Radioplayer, 
 * rights in the Software are licensed (not sold) to subscriber stations, and subscriber stations 
 * have no rights in, or to, the Software other than the right to use it in accordance with the 
 * Terms and Conditions at www.radioplayer.co.uk/terms. You shall not produce any derivate works 
 * based on whole or part of the Software, including the source code, for any other purpose other 
 * than for usage associated with connecting to the UK Radioplayer Service in accordance with these 
 * Terms and Conditions, and you shall not convey nor sublicense the Software, including the source 
 * code, for any other purpose or to any third party, without the prior written consent of UK Radioplayer.
 *
 * @name RadioplayerPresets
 * @description Handles the station presets
 *
 * @param currentStation : {String} id of active station
 *
 * @author Mike Colley <michael.colley@bbc.co.uk>
 * @author Sergejs Vaskevics <sergejs.vaskevics@ubcmedia.com>
 */

radioplayer.models.RadioplayerPresets = function(currentStation) {	
	this._presetData = {};
	this._lastPlayedData = {};
	this._lastPlayed = {};
	this._presets = [];
	this._currentStation = currentStation;
	this._MAXIMUM_PRESET_SPACES = 15;
	this._nodeFactory = new radioplayer.models.StationIconFactory();
	this._presetIsNotAvailable = new Array();
};

radioplayer.models.RadioplayerPresets.prototype = {
	//_presetIsNotAvailable: [],	
	_init: function() {
		var presetLength = radioplayer.utils.object.length(this._presetData),
			i,
			preset;
		this._presets = [];
	    this._lastPlayed = this._nodeFactory._createLastSavedPreset(this._lastPlayedData);
		for ( i=0; i<presetLength; i++ ) {
			var isCurrentStation = this._presetData[i].stationID == this._currentStation;
			preset = this._nodeFactory.createPresetFromStationData(this._presetData[i], false, isCurrentStation);
			this._presets.push(preset);
		}
	},
	
	hasCurrentStation: function(id) {
		return id == this._currentStation;		
	},
	
	isInPresets: function() {
		var isInPresets = false;

		for ( i=0 ; i < this._presets.length ; i++) {
			if (this._presets[i].data('stationID') === this._currentStation) {
			    isInPresets = true;
				break;
			}				
		} 	
		return isInPresets;
	},
	
	hasSpaces: function() {
		var maximumSpaces = this._MAXIMUM_PRESET_SPACES;
		return (this._presets.length < maximumSpaces);
	},
	
	getLastPlayedStation: function() {
		return this._lastPlayed;
	},
	
	getPresets: function() {
		return this._presets;
	},
	
	getPresetCount: function() {
		return this._presets.length;
	},
	
	getRows: function() {
		return this._rows;	
	},	
	
	getCurrentProgrammeInformationForPreset: function(preset,nowPlaying) {
		
		var currentProgrammeTooltip,
			tooltipText = nowPlaying;
		
		currentProgrammeTooltip = this._nodeFactory.createCurrentProgrammeTooltip(tooltipText);
		currentProgrammeTooltip.insertAfter(preset);
		return currentProgrammeTooltip;
		
	},
	
	hideCurrentProgrammeInformationForPreset: function(preset) {
		tooltip = preset.get('.current-programme-panel');
		tooltip.destroy();
	},
	
	addStation: function(id) {
		var isInPresets = false,
			that = this,
			isStationAdded = false;	
		
		for ( i=0 ; i < this._presets.length ; i++) {	
			isInPresets = this._presets[i].data('stationID') == id;				
		}
	
		//if not already in presets
		if (!isInPresets && (this._presets.length < this._MAXIMUM_PRESET_SPACES)) {		
			//is data already in the datastore?
			if (!radioplayer.services.store.isInDatastore(id)) {
				var ids = id;
				if(!this._arrayContainsElement(this._presetIsNotAvailable,id)){
					//request data from webservice
					radioplayer.services.CrossDomain.prototype.getData(ids, {
							onLoad: function() {
								preset = that._createPresetData(ids);
								glow.events.fire(document, 'presets:processWebServiceResponse', {id: id ,preset: preset});
							},
							onError: function() {
								//TODO: ERROR STATE?? MODAL BOX: UNABLE TO ADD PRESET?	
							}								
					});
				}
			} else {
				preset = this._createPresetData(id);
				glow.events.fire(document, 'addstation:data', {p: preset});	
				isStationAdded = true;
			}					
		}
		return isStationAdded;
	},	

	
	_createPresetData: function(id) {
		var preset,
			presetData,
			isCurrentStation;
			
		isCurrentStation = id == this._currentStation;
	
		presetData = radioplayer.services.store.get(id);
		if(presetData){
			presetData.stationID = id;
			preset = this._nodeFactory.createPresetFromStationData(presetData, false, isCurrentStation);
			this._presets.push(preset);
			return preset;
		}
	},	
	
	removePreset: function( preset ) {
		var presetIndex = this._getPresetIndexByPid(this._presets, preset.data('stationID')),
			newPositions = this._presets.slice(),
			callbackFunction,
			dropTargets,
			children,
			animateOptions;
		newPositions.splice(presetIndex, 1);
		
		callBackFunction = function(obj) {
			dropTargets = glow.dom.get('.drop-target');
			dropTargets.each(function() {
				dropTarget = glow.dom.get(this);
				children = dropTarget.children();
				if (children.length === 0) {
					dropTarget.append(obj._nodeFactory.createEmptyPlaceholder());
				}
			});
		};
		
		animateOptions = {reverseAnimate: true, callback: callBackFunction};
		this._animatePresetReordering(newPositions, '', animateOptions);
		
		this._deletePreset(preset);
	},
	
	_deletePreset: function( preset ) {
		var presetIndex = this._getPresetIndexByPid(this._presets, preset.data('stationID'));
		this._presets[presetIndex].destroy();
		preset.destroy();
		this._presets.splice(presetIndex,1);
		
	},

	_getPresetIndexByPid: function( presetArray, id ) {	
		var presetLength = presetArray.length,
			i;
		for (i = 0; i<presetLength; i++) {
			if (presetArray[i].data('stationID')==id) {
				return i;
			}
		}
		return false;                                
	},
	
	isStationAddedToPresets: function(id) {
		return (this._getPresetIndexByPid(this._presets, id)!==false);
	},

	isPresetCurrentStation: function( presetPid ) {
		var presetIndex = this._getPresetIndexByPid(this._presets,presetPid);
		return this._presets[presetIndex].data('isCurrent');
	},
	
	revertChanges: function() {
		this._init();
	},
	
	reorderPresets: function( draggable, droppable, draggableObject ) {
		var draggablePid =  draggable.attr('id').split('_').pop(),
			droppableId = droppable.get('.station-icon').attr('id'),
			oldIndex = this._getPresetIndexByPid(this._presets, draggablePid),
			newIndex,
			presetHasMovedBackwards,
			animateOptions,
			newPositions,
			movedPreset;
		
		// Find the new position of the preset
		
		// if dropTargetId is empty, then it's been moved to an empty placeholder, so we place it at the end
		if (droppableId===null || droppableId.length===0) {
			newIndex = (this._presets.length-1);
		}
		else {
			// Moved over 'last played' : treat as moving to start of presets
			if (droppable.attr('id')=='last-played') {
				newIndex=0;
			}
			else {
				newIndex= this._getPresetIndexByPid(this._presets,droppableId.split('_').pop());
			}			
		}
		
		// Return false if the preset hasn't been moved
		if (oldIndex==newIndex) {
			return false;
		}

		presetHasMovedBackwards = (oldIndex > newIndex);
		animateOptions = { reverseAnimation: presetHasMovedBackwards,
							drag: draggable,
							drop: droppable							
						};
		
		// Make a copy of the presets array, remove the moved preset form its old position and insert it into the new position
		newPositions = this._presets.slice();
		movedPreset = newPositions.splice(oldIndex,1);
		newPositions.splice(newIndex,0,movedPreset[0]);

		this._animatePresetReordering(newPositions, draggablePid, animateOptions);
		
		this._presets = newPositions;
		return this._presets.length;
	},	
	
	_animatePresetReordering: function( newPositions, draggablePid, opts ) {
		var radioplayerpresets = this,
			myAnims =[],
			animArray,
			toIndex,
			positionObject,
			iconsToSwap = [], 
			iconIndex=0,
			icons,
			duration=0.3, // Duration of animation in seconds.
			animationStaggering = 0.2, // time between consecutive animations starting, in seconds
			i,
			timeline,
			presetLength = this._presets.length;
			
		// step through the presets and see where each has moved to
		for ( i = 0 ; i < presetLength ; i++) {			

		    toIndex = this._getPresetIndexByPid(newPositions,this._presets[i].data('stationID'));
		    
		    if (toIndex !== false && toIndex != i &&(i < this._MAXIMUM_PRESET_SPACES)) {
				icons = {
						fromPreset:  this._presets[i],	
						toPreset:	 this._presets[toIndex],
						toParent:	 this._presets[toIndex].parent()
				};

				if (icons.fromPreset.data('stationID')!=draggablePid) {
					positionObject = this._getAnimationPositions(icons.fromPreset, icons.toPreset);

					animArray = [];
					animArray.push(animationStaggering*iconIndex);
					animArray.push(glow.anim.css(icons.fromPreset, duration, {
								left : positionObject.left,
								top  : positionObject.top
								}, {
									tween: glow.tweens.easeBoth(5)
								}
								));
					myAnims.push(animArray);
					
				}
				iconsToSwap[iconIndex++] = icons;
			}	
		}

		if (opts.reverseAnimation) {
			myAnims.reverse();
		}
		timeline = new glow.anim.Timeline(myAnims, {
				destroyOnComplete:true,
				onComplete: function () {
					radioplayerpresets._swapIconContainers(iconsToSwap,newPositions);
					glow.events.fire(document, 'ondrag:false');	

					if (opts.callback) {
						opts.callback(radioplayerpresets);
					}
				}
		});
		
		timeline.start();		
	},
	
	
	// Moves preset from old container (station-container class) to new container in the DOM
	_swapIconContainers: function( iconsToSwap) {		
		var i, 
			iconsLength = iconsToSwap.length;
		for ( i = 0 ; i < iconsLength ; i++) {
			iconsToSwap[i].fromPreset.css( {
											left:'',
											top : '',
											position : '',
											'z-index' : ''
				});
			iconsToSwap[i].toParent.append(iconsToSwap[i].fromPreset);
		}		
		return this._presets.length;
	},
	
	
	// Find start and end positions for each icon
	_getAnimationPositions: function( fromIcon, toIcon) {
		if(!fromIcon || !toIcon) {

		}
		var fromOffset 		 = fromIcon.offset(),
			fromParentOffset = fromIcon.parent().offset(),
			toParentOffset	 = toIcon.parent().offset();
		
		var fromLeft	= fromOffset.left		 - fromParentOffset.left,
			toLeft 		= toParentOffset.left    - fromParentOffset.left,
			fromTop 	= fromOffset.top 		 - fromParentOffset.top,
			toTop 		= toParentOffset.top	 - fromParentOffset.top;
		
		var positionObject = {
								left: { from: fromLeft, to: toLeft},
								top:  { from: fromTop , to: toTop }
							};
		return positionObject;
		
	},
	
	saveChanges: function() {
		var i,
			presetLength = this._presets.length,
			preset,
			cookiedata;
			
		this._presetData = {};
		cookiedata = [];
		
		for ( i = 0 ; i < presetLength; i++) {
			preset = this._presets[i];
			cookiedata.push(i + ':' + preset.data('stationID'));
			
			this._presetData[i] = {
									stationID:preset.data('stationID'),
									name:preset.data('name'),
									logoUrl:preset.data('logoUrl'),
									playerUrl:preset.data('playerUrl')								
								  };			
		}

		return cookiedata;
	},
	_arrayContainsElement: function(array,element){
		var i; 
		for(i=0; i < array.length; i++){ 
			if(array[i] === element){
				return true; 	
			}
		} 
		return false; 
	}
	

	
};

