/* Copyright 2009 Palm, Inc.  All rights reserved. */

function AppAssistant(appController) {
	//this.alarm = new Alarm(12);
	
	this.alarms = new Alarms();
	this.settings = new Settings();
	this.themes = new Themes();
	this.updateOnTimezoneChange();
	
	this.lastTz = undefined;
	
	
}

AppAssistant.prototype.kRingStageName = 'ring';

AppAssistant.prototype.handleLaunch = function(params) {
	
	Mojo.Log.logProperties(params);
	
	if (params && params.action) {
		switch (params.action) {
			case "ring":
				this.ring(params);
				return;
			case "update":
				Mojo.Log.error("launching for update");
				this.updateOnTimezoneChange();
				return;
			default:
				Mojo.Log.info("unknown launch parameter");
				this.launchClock();
				break;
		}
	} else {
		this.launchClock();
	}
		
};

// if the timezone is different than the last time we updated, 
// resave alarms to service
AppAssistant.prototype.updateOnTimezoneChange = function() {
	this.timezoneRequest = new Mojo.Service.Request(AppAssistant.kSystemServiceTimeUri, {
		method: "getSystemTime",
		parameters: {
			"subscribe":false
		},
		onSuccess: function(payload) {
			if (this.lastTz === undefined) {
				this.lastTz = payload.offset;
			} else if (this.lastTz != payload.offset) {
				this.lastTz = payload.offset;
				this.alarms = new Alarms(); // happens automatically on load of each alarm
				this.refreshAlarms();
			}
		}.bind(this),
		onFailure: function() {
			Mojo.Log.error("Alarm: can't connect to system service");				
		}.bind(this)
	});
	
};

// causes clock to be launched when timezone changes or time changes significantly
AppAssistant.prototype.registerForTimeChanges  = function() {
	this.timeChangeRegisterRequest = new Mojo.Service.Request(AppAssistant.kSystemServiceTimeUri, {
		method: "setTimeChangeLaunch",
		parameters: {
			"appId":"com.palm.app.clock", 
			"parameters":{
				"action":"update"
			}
		},
		onSuccess: function(payload) {
			Mojo.Log.info("Clock: registered for timezone changes");
		},
		onFailure: function() {
			Mojo.Log.error("Clock: can't register for time changes");				
		}
	});
	
}

AppAssistant.prototype.launchClock = function(sceneParams) {
	var clockStage = this.controller.getStageController('clock');

	if (clockStage) {
		clockStage.window.focus(); 
		if (sceneParams) {
			clockStage.delegateToSceneAssistant("showScene", sceneParams);
		}
	} else {
		// Make sure Themes is reset whenever the stage needs to be created
		this.themes = new Themes();
		this.registerForTimeChanges();
		var f = function(stageController) {
			stageController.pushScene('clock', sceneParams);
		}.bind(this);
		this.controller.createStageWithCallback({name: 'clock', lightweight: true}, f);		
	}
};


AppAssistant.prototype.launchAlarmList = function() {
	this.launchClock({"scene":"list"});
};


AppAssistant.prototype.launchAlarmDetails = function(id) {
	this.launchClock({"alarmId":id});
}

AppAssistant.prototype.createRingStage = function createRingStage(params, callsResponse) {
	var soundClass = "alarm";
	var soundFile = params.alarm.alarmSoundFile;
	var checkPhoneCallRequest = this.checkPhoneCallRequest;
	if (checkPhoneCallRequest) {
		checkPhoneCallRequest.cancel();
		delete this.checkPhoneCallRequest;		
	}
	callsResponse = callsResponse.macroEventCalls;
	// use alert if we're on a call
	if (callsResponse && (callsResponse.singleHold || callsResponse.singleActive)) {
		soundClass = "alert";
		soundFile = undefined;
	// if the ringer switch is respected, use ringtones
	} else if (this.settings.ringerSwitchObeyedGet()) {
		soundClass = "ringtones";  // TODO FIXME: get a better soundclass
	}
	
	var f = function(stageController) {
		stageController.pushScene('ring', params);
	};
	this.controller.createStageWithCallback({
		lightweight: true,
		name: this.kRingStageName, 
		"height": 200, 
		soundclass: soundClass,
		sound: soundFile
	}, f, 'popupalert');		
};

AppAssistant.prototype.ring = function(params) {
	
	if (!params) {
		params = {};
	}
	
	Mojo.Log.error("Ringing alarm: ", params.id);
		
	var alarm = this.alarms.findAlarmByID(params.id);
	
	if (!alarm) {
		Mojo.Log.error("Alarm: deleted alarm attempted to ring");
		return;
	}
	
	if (!alarm.enabled) {
		Mojo.Log.error("Alarm: disabled alarm attempted to ring");
		return;
	}
	
	var now = new Date();
	
	if (alarm.time) {
		var offset = alarm.time.getHours() - now.getHours();
		if (offset < -1 || offset > 1) {
			Mojo.Log.error("Alarm: rang more than an hour before/after it should have. ignoring.");
			return;	
		}
	} else {
		Mojo.Log.error("Alarm: no time");
		return;
	}
	params.alarm = alarm;
	
	var ringStage = this.controller.getStageProxy(this.kRingStageName);

	if (ringStage) {
		// TODO ringStage.delegateToSceneAssistant(stageName, params) 
	} else {
		var getCallsParams = {
			onSuccess: this.createRingStage.bind(this, params),
			onFailure: this.createRingStage.bind(this, params, {})
		};
		this.checkPhoneCallRequest = new Mojo.Service.Request(AppAssistant.kGetAllCallsUri, getCallsParams);
	}
};

AppAssistant.prototype.refreshAlarms = function() {
	this.refreshAlarmsInClockStage();
	this.updateAlarmDashboard();
};

AppAssistant.prototype.refreshAlarmsInClockStage = function() {
	var clockStage = this.controller.getStageController('clock');

	if (clockStage) {
		clockStage.delegateToSceneAssistant("refreshAlarms");
	}
};

AppAssistant.prototype.updateAlarmDashboard = function() {
	var stageName = "alarmdash";
	
	var dashStage = this.controller.getStageProxy(stageName);

	if (dashStage) {
		dashStage.delegateToSceneAssistant("update");
	} else {
		if (this.alarms.countEnabledAlarms() === 0 || this.settings.dashboardHideGet()) {
			return;
		}
		var f = function(stageController){
			stageController.pushScene('alarmdash');
		};
		this.controller.createStageWithCallback({
			lightweight: true,
			name: stageName,
			icon: "images/notification-alarm-small.png"
		}, f, 'dashboard');
	}
};

AppAssistant.kSystemServiceTimeUri = "palm://com.palm.systemservice/time";
AppAssistant.kGetAllCallsUri = "palm://com.palm.telephony/callsGetAll";
