- Add support for "!wm <value>" and "!wm <name>" commands.
[reactos.git] / irc / TechBot / TechBot.Library / WmCommand.cs
1 using System;
2 using System.Xml;
3
4 namespace TechBot.Library
5 {
6 public class WmCommand : BaseCommand, ICommand
7 {
8 private IServiceOutput serviceOutput;
9 private string wmXml;
10 private XmlDocument wmXmlDocument;
11
12 public WmCommand(IServiceOutput serviceOutput,
13 string wmXml)
14 {
15 this.serviceOutput = serviceOutput;
16 this.wmXml = wmXml;
17 wmXmlDocument = new XmlDocument();
18 wmXmlDocument.Load(wmXml);
19 }
20
21 public bool CanHandle(string commandName)
22 {
23 return CanHandle(commandName,
24 new string[] { "wm" });
25 }
26
27 public void Handle(MessageContext context,
28 string commandName,
29 string parameters)
30 {
31 string wmText = parameters;
32 if (wmText.Equals(String.Empty))
33 {
34 serviceOutput.WriteLine(context,
35 "Please provide a valid window message value or name.");
36 return;
37 }
38
39 NumberParser np = new NumberParser();
40 long wm = np.Parse(wmText);
41 string output;
42 if (np.Error)
43 {
44 // Assume "!wm <name>" form.
45 output = GetWmNumber(wmText);
46 }
47 else
48 {
49 output = GetWmDescription(wm);
50 }
51
52 if (output != null)
53 {
54 serviceOutput.WriteLine(context,
55 String.Format("{0} is {1}.",
56 wmText,
57 output));
58 }
59 else
60 {
61 serviceOutput.WriteLine(context,
62 String.Format("I don't know about window message {0}.",
63 wmText));
64 }
65 }
66
67 public string Help()
68 {
69 return "!wm <value> or !wm <name>";
70 }
71
72 private string GetWmDescription(long wm)
73 {
74 XmlElement root = wmXmlDocument.DocumentElement;
75 XmlNode node = root.SelectSingleNode(String.Format("WindowMessage[@value='{0}']",
76 wm));
77 if (node != null)
78 {
79 XmlAttribute text = node.Attributes["text"];
80 if (text == null)
81 throw new Exception("Node has no text attribute.");
82 return text.Value;
83 }
84 else
85 return null;
86 }
87
88 private string GetWmNumber(string wmName)
89 {
90 XmlElement root = wmXmlDocument.DocumentElement;
91 XmlNode node = root.SelectSingleNode(String.Format("WindowMessage[@text='{0}']",
92 wmName));
93 if (node != null)
94 {
95 XmlAttribute value = node.Attributes["value"];
96 if (value == null)
97 throw new Exception("Node has no value attribute.");
98 return value.Value;
99 }
100 else
101 return null;
102 }
103 }
104 }