[DDK]
[reactos.git] / irc / TechBot / TechBot.Library / TechBotService.cs
1 using System;
2 using System.Collections;
3 using System.Collections.Generic;
4 using System.IO;
5 using System.Data;
6 using System.Threading;
7
8 using TechBot.IRCLibrary;
9
10 namespace TechBot.Library
11 {
12 public abstract class TechBotService
13 {
14 protected IServiceOutput m_ServiceOutput;
15
16 public TechBotService(IServiceOutput serviceOutput)
17 {
18 m_ServiceOutput = serviceOutput;
19 }
20
21 public virtual void Run()
22 {
23 CommandFactory.LoadPlugins();
24 }
25
26 public IServiceOutput ServiceOutput
27 {
28 get { return m_ServiceOutput; }
29 }
30
31 public CommandBuilderCollection Commands
32 {
33 get { return CommandFactory.Commands; }
34 }
35
36 public void InjectMessage(MessageContext context, string message)
37 {
38 ParseCommandMessage(context,
39 message);
40 }
41
42 private bool IsCommandMessage(string message)
43 {
44 return message.StartsWith(Settings.Default.CommandPrefix);
45 }
46
47 public void InjectMessage(string message)
48 {
49 ParseCommandMessage(null, message);
50 }
51
52 public void ParseCommandMessage(MessageContext context,
53 string message)
54 {
55 if (!IsCommandMessage(message))
56 return;
57
58 message = message.Substring(1).Trim();
59 int index = message.IndexOf(' ');
60 string commandName;
61 string commandParams = "";
62 if (index != -1)
63 {
64 commandName = message.Substring(0, index).Trim();
65 commandParams = message.Substring(index).Trim();
66 }
67 else
68 commandName = message.Trim();
69
70 foreach (CommandBuilder command in Commands)
71 {
72 if (command.Name == commandName)
73 {
74 //Create a new instance of the required command type
75 Command cmd = command.CreateCommand();
76
77 cmd.TechBot = this;
78 cmd.Context = context;
79 cmd.Parameters = commandParams;
80
81 try
82 {
83 cmd.Initialize();
84 cmd.Run();
85 cmd.DeInitialize();
86 }
87 catch (Exception e)
88 {
89 ServiceOutput.WriteLine(context, string.Format("Uops! Just crashed with exception '{0}' at {1}",
90 e.Message,
91 e.Source));
92
93 ServiceOutput.WriteLine(context, e.StackTrace);
94 }
95
96 return;
97 }
98 }
99 }
100 }
101 }