/**
 * 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 currentlyOnAir
 * @description Retrieves currently playing programmes/programme events from search service
 *
 *
 * @author Sergejs Vaskevics <sergejs.vaskevics@ubcmedia.com>
 */

radioplayer.controllers.CurrentlyOnAir = function() {
	this._presetIdArray = [];
	this._lastPlayedStationID = radioplayer.currentStationID;
	this._nowPlayingDataNotAvailable = new Array();
	this._releaseRequestLockTimeout = {};
	this.bind();  
};

radioplayer.controllers.CurrentlyOnAir.prototype = {
		_lastRequestTimeInEpochSeconds : {},
		_callback : {},
		_requestedStationId : "",
		_requestedPreset : {},		
		_requestSent : false,
		
		"presets:getNowPlayingInfo subscribe": function(obj) {
			var preset = obj.preset; 
			var callback = obj.callback;
			this._requestedPreset = preset;
			this._requestedStationId = this._getStationId(preset);
			if((this._requestedStationId == null)||(this._arrayContainsElement(this._nowPlayingDataNotAvailable,this._requestedStationId))){
				return;
			}
			var dataStorage = radioplayer.controllers.CurrentlyOnAir.dataStorage;
			this._callback = callback;
			
			if(!dataStorage || !(dataStorage.isInDatastore(this._requestedStationId))){
				//no data storage, or requested id is not in there
				this.requestPresetsNowPlaying();
				return;
			}
			var nowInEpochSeconds = this._getTimeInEpochSeconds(0);			
			var fifteenMinutesInEpochSeconds = 900;
			timePassedSinceLastRequest = nowInEpochSeconds - this._lastRequestTimeInEpochSeconds;
			
			var nowPlayingData = dataStorage.get(this._requestedStationId);
			if(nowPlayingData.stopTimeEpoch == ""){
				if(timePassedSinceLastRequest > fifteenMinutesInEpochSeconds){
					//no end date specified and last req more then 15 min ago
					this.requestPresetsNowPlaying();
					return;
				}else{
					glow.events.fire(document, 'presets:returnNowPlayingInfo', {data:nowPlayingData.nowPlayingName});
					return;
				}
			}
			if(nowPlayingData.stopTimeEpoch > nowInEpochSeconds){
				glow.events.fire(document, 'presets:returnNowPlayingInfo', {data:nowPlayingData.nowPlayingName});
			}else{
				//if data is old 
				this.requestPresetsNowPlaying();
				return;	
			}
		},
		"presets:returnNowPlayingInfo subscribe": function(obj) {		
			if(this._callback){
				this._callback.onLoad(obj.data);
			}
		},
		"presets:processResponse subscribe": function() {
			clearTimeout(this._releaseRequestLockTimeout);
			
			var dataStorage = radioplayer.controllers.CurrentlyOnAir.dataStorage;
			
			if(dataStorage.isInDatastore(this._requestedStationId)){
				var nowInEpochSeconds = this._getTimeInEpochSeconds(0);
				var requestedInfo = dataStorage.get(this._requestedStationId);
				if(requestedInfo.stopTimeEpoch > nowInEpochSeconds || requestedInfo.stopTimeEpoch == ""){
					glow.events.fire(document, 'presets:returnNowPlayingInfo', {data:requestedInfo.nowPlayingName});
				}
			}else{
				if(!(this._requestedStationId in this._nowPlayingDataNotAvailable)){
					this._nowPlayingDataNotAvailable.push(this._requestedStationId);
				}
			}
			this._requestSent = false;
		},
		"presets:releaseRequestLock subscribe": function() {		
			this._requestSent = false;	
		},
		//presets data received from cookie and data successfully loaded from webservice
		'presets:data subscribe': function(obj) {
			var presets,i;
			var self = this;
			
			//if there are presets (ie not null (NB null is a string as returned from the cookie))
			//parse the cookiedata ids with the datastore
			obj.d == 'null' ? presets = {} : presets = radioplayer.utils.parseData(obj.d);
			var pr = presets;
			for(i in presets){
				if(presets[i].stationID){
						this._presetIdArray.push(presets[i].stationID);
				}
			}
		},
		//lastplayed data received from cookie and data successfully loaded from webservice
		'lastplayed:data subscribe': function(obj) {
			var lastplayed = {},
				currentstation = [this._currentStation];
			
			if (obj.d == 'null') {
				this._lastPlayedStationID = radioplayer.currentStationID;
			} else {
				this._lastPlayedStationID = obj.d;
			}	
		},
		'addstation:data subscribe': function(obj) {
			var preset = obj.p,
				stationID = preset.data('stationID');
			if(stationID){
				if(!this._arrayContainsElement(this._presetIdArray ,stationID)){
					this._presetIdArray.push(stationID);
				}
			}
		},
		requestPresetsNowPlaying:function(){
			if(this._requestSent){
				//request canceled, because request lock has value true
				return;
			}
			this._requestSent = true;
			
			var nowInEpochSeconds = this._getTimeInEpochSeconds(0);
			this._lastRequestTimeInEpochSeconds = nowInEpochSeconds;
			var endTime = nowInEpochSeconds + 120;
			
			var baseUrl = radioplayer.searchServerBaseUrl+"query.jsp?";
			var stationIdString = this._getPresetsIdsRequestStr();
			
			var requestURL = "stationIDList=" + stationIdString;

			this._releaseRequestLockTimeout = setTimeout(function() { glow.events.fire(document, 'presets:releaseRequestLock'); }, 10000);
			glow.net.loadScript(baseUrl + requestURL );
		},
		processPresetsNowPlayingResponse:function(data){
			if(data){
				var processedData = this._extractNearestToCurrentTime(data);
				radioplayer.controllers.CurrentlyOnAir.dataStorage = new radioplayer.services.Datastore(processedData);
				glow.events.fire(document, 'presets:processResponse', {});
			}
			
		},
		_extractNearestToCurrentTime: function(data){
			var dataResp = data.results;
			var dataToReturn = {};
			var curStationId = "";
			var curStationRec = {};
			for (id in dataResp) {
				curStationRec = {};
				curStationId = dataResp[id].stationID;
				if (curStationId in dataToReturn) {
					if((dataToReturn[curStationId].startTimeEpoch == "" )||(dataToReturn[curStationId].stopTimeEpoch == "" )){
						if(!this._isHistoricalDate(dataResp[id].stopTimeEpoch)){
							curStationRec = this._changeResponseRecordStructure(dataResp[id]);
							dataToReturn[curStationId] = glow.lang.apply(dataToReturn[curStationId], curStationRec);
						}
					}else if(dataToReturn[curStationId].stopTimeEpoch > dataResp[id].stopTimeEpoch){
						if(!this._isHistoricalDate(dataResp[id].stopTimeEpoch)){
							curStationRec = this._changeResponseRecordStructure(dataResp[id]);
							dataToReturn[curStationId] = glow.lang.apply(dataToReturn[curStationId], curStationRec);
						}
					}
				}
				else {
					curStationRec = this._changeResponseRecordStructure(dataResp[id]);
					dataToReturn[curStationId] = glow.lang.clone(curStationRec);
				}
			}
			
			return dataToReturn ;
		},
		_changeResponseRecordStructure: function(rec){
			var recToReturn = {};
			if ( rec.nowPlayingArtist != "" ) {
				recToReturn.nowPlayingName = rec.nowPlayingArtist + ", " + rec.nowPlayingName
			}
			else recToReturn.nowPlayingName = rec.nowPlayingName;
			recToReturn.startTimeEpoch = rec.startTimeEpoch;
			recToReturn.stopTimeEpoch = rec.stopTimeEpoch;
			
			return recToReturn;
		},
		_getPresetsIdsRequestStr  : function() {
			var returnIdsStr = "";
			if(!this._arrayContainsElement(this._presetIdArray,this._lastPlayedStationID )){
				returnIdsStr = this._lastPlayedStationID;
				if(this._presetIdArray.length){
					returnIdsStr = returnIdsStr + ",";

				}
			}
			return returnIdsStr+this._presetIdArray.join(",");
		},
		_getStationId: function(preset){
			var stationId = null;
			if(preset[0]){
				if(preset[0].id){
					if(preset[0].id === "last-played-station-icon"){
						stationId = this._lastPlayedStationID;
					}else{
						stationId = parseInt(preset[0].id.split('_')[1]);
					}
				}
			}
			return stationId;
		},
		_arrayContainsElement: function(array,element){
			var i; 
			for(i=0; i < array.length; i++){ 
				if(array[i] === element){
					return true; 	
				}
			} 

			return false; 
		},
		_isHistoricalDate: function(dateInEpochSeconds){
			var nowInEpoch = this._getTimeInEpochSeconds(0);
			var dateInEpochMinusNow = dateInEpochSeconds - nowInEpoch ;
			return (dateInEpochMinusNow < 0 ); 
		},
		
		_getTimeInEpochSeconds: function(timeModifierInEpochSeconds){
			var now = new Date(),
			 	nowInEpochSeconds = Math.round(now.getTime()* 0.001),
			 	returnTimeValue = nowInEpochSeconds + timeModifierInEpochSeconds;
						
			return returnTimeValue;
		}
				
};

