Value ServiceGroupsTable::NumServicesAccessor(const Value& row)
{
	ServiceGroup::Ptr sg = static_cast<ServiceGroup::Ptr>(row);

	if (!sg)
		return Empty;

	return sg->GetMembers().size();
}
Value ServiceGroupsTable::NumServicesHardUnknownAccessor(const Value& row)
{
	ServiceGroup::Ptr sg = static_cast<ServiceGroup::Ptr>(row);

	if (!sg)
		return Empty;

	int num_services = 0;

	for (const Service::Ptr& service : sg->GetMembers()) {
		if (service->GetStateType() == StateTypeHard && service->GetState() == ServiceUnknown)
			num_services++;
	}

	return num_services;
}
Value ServiceGroupsTable::NumServicesPendingAccessor(const Value& row)
{
	ServiceGroup::Ptr sg = static_cast<ServiceGroup::Ptr>(row);

	if (!sg)
		return Empty;

	int num_services = 0;

	for (const Service::Ptr& service : sg->GetMembers()) {
		if (!service->GetLastCheckResult())
			num_services++;
	}

	return num_services;
}
Value ServiceGroupsTable::NumServicesCritAccessor(const Value& row)
{
	ServiceGroup::Ptr sg = static_cast<ServiceGroup::Ptr>(row);

	if (!sg)
		return Empty;

	int num_services = 0;

	for (const Service::Ptr& service : sg->GetMembers()) {
		if (service->GetState() == ServiceCritical)
			num_services++;
	}

	return num_services;
}
Value ServiceGroupsTable::WorstServiceStateAccessor(const Value& row)
{
	ServiceGroup::Ptr sg = static_cast<ServiceGroup::Ptr>(row);

	if (!sg)
		return Empty;

	Value worst_service = ServiceOK;

	for (const Service::Ptr& service : sg->GetMembers()) {
		if (service->GetState() > worst_service)
			worst_service = service->GetState();
	}

	return worst_service;
}
void ServiceGroupDbObject::OnConfigUpdate(void)
{
	ServiceGroup::Ptr group = static_pointer_cast<ServiceGroup>(GetObject());

	BOOST_FOREACH(const Service::Ptr& service, group->GetMembers()) {
		DbQuery query1;
		query1.Table = DbType::GetByName("ServiceGroup")->GetTable() + "_members";
		query1.Type = DbQueryInsert;
		query1.Category = DbCatConfig;
		query1.Fields = make_shared<Dictionary>();
		query1.Fields->Set("instance_id", 0); /* DbConnection class fills in real ID */
		query1.Fields->Set("servicegroup_id", DbValue::FromObjectInsertID(group));
		query1.Fields->Set("service_object_id", service);
		OnQuery(query1);
	}
}
Value ServiceGroupsTable::MembersAccessor(const Value& row)
{
	ServiceGroup::Ptr sg = static_cast<ServiceGroup::Ptr>(row);

	if (!sg)
		return Empty;

	ArrayData result;

	for (const Service::Ptr& service : sg->GetMembers()) {
		result.push_back(new Array({
			service->GetHost()->GetName(),
			service->GetShortName()
		}));
	}

	return new Array(std::move(result));
}