#include "StdAfx.h"
#include "group.h"
#include "ATLComTime.h"

Group::Group()
{
	idletime = 0;
	popup.Hide();
	popup.Create();
	item = NULL;
	editing = 0;
}

Group::~Group(void)
{
}

// these things change due to time 
void Group::ShallowRefresh()
{

	int active = !record.Idle;

	COleDateTime now = COleDateTime::GetCurrentTime();
	// adjust the local time to match the server time
	now += rpc.TimeAdjustment;
	COleDateTime idleSince(record.IdleSince);
	COleDateTimeSpan idlespan = (now-idleSince);

	idletime = idlespan.GetTotalSeconds()/60.0;

	TCHAR buffer[1023];
	// update the associated popup list
	popup.titlebar.title = lrecord.LocationName;
	popup.titlebar.title += L" : ";
	if(active){
		_stprintf(buffer,L"online %s",ConvertTimeSpanToCompactString(idlespan));
		popup.titlebar.title += theApp.grouplist.Active.description;
	} else {
		_stprintf(buffer,L"idle %s",ConvertTimeSpanToCompactString(idlespan));
		popup.titlebar.title += theApp.grouplist.Idle.description;
	}
	popup.subtitle.title = buffer;
	popup.Redraw();

	// update the associated item's style
	if(item){
		if(editing){
			if(checked)
				item->Set(theApp.grouplist.Checked);
			else
				item->Set(theApp.grouplist.Unchecked);
		} else {
			if(active)
				item->Set(theApp.grouplist.Active);
			else
				item->Set(theApp.grouplist.Idle);
		}
		item->Redraw();
	}
}

void Group::DeepRefresh(int groupId)
{
	switch(db.GetGroup(groupId,record)){
		case dbException:
			print(L"Group::DeepRefresh - DB exception\n");
			break;
		case dbInvalidParam:
			print(L"Group::DeepRefresh - unknown group (groupId=%d)\n",groupId);
			break;
		case dbSuccess:
			if(editing)
				popup.DeepRefresh(record.GroupId,1);
			else
				popup.DeepRefresh(record.GroupId,0);

			db.GetCachedLocation(record.LocationId,lrecord);

			Vector<int> members;
			db.GetGroupMembers(groupId,members);
			checked = members.find(theApp.user.UserId)!=-1;

			ShallowRefresh();
			break;
	}
}

void Group::OnCustomNotify(int id, Notification& n)
{
	switch(id){
	case bcGroup:		
		DeepRefresh(record.GroupId);
		break;
	}

}