summaryrefslogtreecommitdiff
path: root/include/service.h
blob: 949e7b1a150a7881d4deca31ab46857574109eb5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
/*
 * (C) 2003-2012 Anope Team
 * Contact us at team@anope.org
 *
 * Please read COPYING and README for further details.
 *
 * Based on the original code of Epona by Lara.
 * Based on the original code of Services by Andy Church.
 */

#ifndef SERVICE_H
#define SERVICE_H

#include "services.h"
#include "anope.h"
#include "modules.h"

class CoreExport Service : public virtual Base
{
	static Anope::map<Anope::map<Service *> > services;
 public:
 	static Service *FindService(const Anope::string &t, const Anope::string &n)
	{
		Anope::map<Anope::map<Service *> >::iterator it = services.find(t);
		if (it != services.end())
		{
			Anope::map<Service *>::iterator it2 = it->second.find(n);
			if (it2 != it->second.end())
				return it2->second;
		}

		return NULL;
	}

	static std::vector<Anope::string> GetServiceKeys(const Anope::string &t)
	{
		std::vector<Anope::string> keys;
		Anope::map<Anope::map<Service *> >::iterator it = services.find(t);
		if (it != services.end())
			for (Anope::map<Service *>::iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2)
				keys.push_back(it2->first);
		return keys;
	}

	Module *owner;
	Anope::string type;
	Anope::string name;

	Service(Module *o, const Anope::string &t, const Anope::string &n) : owner(o), type(t), name(n)
	{
		this->Register();
	}

	virtual ~Service()
	{
		this->Unregister();
	}

	void Register()
	{
		Anope::map<Service *> &smap = services[this->type];
		if (smap.find(this->name) != smap.end())
			throw ModuleException("Service " + this->type + " with name " + this->name + " already exists");
		smap[this->name] = this;
	}

	void Unregister()
	{
		Anope::map<Service *> &smap = services[this->type];
		smap.erase(this->name);
		if (smap.empty())
			services.erase(this->type);
	}
};

template<typename T>
class service_reference : public dynamic_reference<T>
{
	Anope::string type;
	Anope::string name;

 public:
	service_reference(const Anope::string &t, const Anope::string &n) : dynamic_reference<T>(NULL), type(t), name(n)
	{
	}

	inline void operator=(const Anope::string &n)
	{
		this->name = n;
	}

	operator bool() anope_override
	{
		if (this->invalid)
		{
			this->invalid = false;
			this->ref = NULL;
		}
		if (!this->ref)
		{
			this->ref = static_cast<T *>(Service::FindService(this->type, this->name));
			if (this->ref)
				this->ref->AddReference(this);
		}
		return this->ref;
	}
};

#endif // SERVICE_H