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

var AlarmdashAssistant = Class.create({
	initialize: function() {
		this.appControl = Mojo.Controller.getAppController();
		this.appAssistant = this.appControl.assistant;
		this.alarms = this.appAssistant.alarms;
		this.onActivate = this.onActivate.bind(this);
		this.windowName = "alarmdash"
 	},
  
  setup: function() {
		this.controller.get('icon-action').addEventListener(Mojo.Event.tap, this.onIconTap.bindAsEventListener(this));
		this.controller.get('text-action').addEventListener(Mojo.Event.tap, this.onMessageTap.bindAsEventListener(this));
		this.controller.listen(this.controller.document, Mojo.Event.stageActivate, this.onActivate);
		this.update();
  },


  // run callback and close this
  onIconTap: function () {
	Mojo.Log.info( "AlarmdashAssistant::onTap", "windowName:" , this.windowName);
	this.appAssistant.launchAlarmList();
  },
  
  onMessageTap: function () {
	Mojo.Log.info( "AlarmdashAssistant::onTap", "windowName:" , this.windowName);
	this.appAssistant.launchAlarmDetails(this.earliestAlarm.id);
  },
  
  onActivate: function() {
  	Mojo.Log.info("AlarmdashAssistant:onActivate");
	this.update();
  },
  
  update: function() {
  	this.alarms = this.appAssistant.alarms;
  	var alarmCount = this.alarms.countEnabledAlarms();
	if (alarmCount > 0) {
		this.earliestAlarm = this.alarms.getEarliestEnabledAlarm();
		
	  	this.controller.get('title').textContent = this.earliestAlarm.title;
		this.controller.get('message').textContent = new Template(AlarmdashAssistant.kMessage).evaluate({"time":this.earliestAlarm.niceTime, "day":this.earliestAlarm.nextAlarmDayText()});
		this.updateBadge(alarmCount);
	} else {
		this.closeWindow();
	}
  },
  
  updateBadge: function(itemcount) {
  	   if (itemcount > 1) {
	   		Mojo.Log.info("AlarmdashAssistant::updateBadge", itemcount);
			this.controller.get('notification').removeClassName("single")
			this.controller.get('itemcount').show();
			this.controller.get('itemcounttext').innerHTML = itemcount;
	   } else {
	   		this.controller.get('notification').addClassName("single");
	   		this.controller.get('itemcount').hide();
	   }
  },
  
  closeWindow: function() {
 	Mojo.Controller.getAppController().closeStage(this.windowName);
  }
  
});

AlarmdashAssistant.kMessage = "#{time} #{day}";
