Added "search" architecture
[WebThing.git] / SearchHandler.cs
1 using System;
2 using System.Collections.Generic;
3 using System.Text.RegularExpressions;
4
5 namespace bytex64.WebThing {
6     public class SearchHandler {
7         WebThing wt;
8         Dictionary<string,ISearchPlugin> Handlers;
9         
10         public SearchHandler(WebThing wt) {
11             Handlers = new Dictionary<string,ISearchPlugin>();
12             this.wt = wt;
13
14             foreach (SearchHandlerPair p in Config.SearchHandlers) {
15                 AddHandler(p.Shortcut, p.Plugin);
16             }
17         }
18
19         public void AddHandler(string key, string plugin) {
20             if (Handlers.ContainsKey(key)) {
21                 Console.WriteLine("Cannot add search handler {0}: shortcut {1} already registered", plugin, key);
22                 return;
23             }
24             if (!wt.Plugins.Plugins.ContainsKey(plugin)) {
25                 Console.WriteLine("Cannot add search handler {0}: Plugin for {0} not loaded", plugin);
26                 return;
27             }
28
29             WebThingPlugin p = wt.Plugins.Plugins[plugin];
30             Type ptype = p.GetType();
31
32             if (ptype.GetInterface("ISearchPlugin") != null) {
33                 Handlers[key] = (ISearchPlugin) p;
34                 Console.WriteLine("Added handler {0} for key {1}", plugin, key);
35             } else {
36                 Console.WriteLine("Cannot add search handler {0}: {0} Does not implement ISearchPlugin", plugin);
37             }
38         }
39
40         // Call a search handler based on the leading word
41         public string Transform(string search) {
42             Regex get_handler_re = new Regex(@"^([\w-]+)\s+");
43             Match m = get_handler_re.Match(search);
44             if (m.Success) {
45                 string key = m.Groups[1].Value;
46                 string query = get_handler_re.Replace(search, "");
47                 if (!Handlers.ContainsKey(key)) {
48                     Console.WriteLine("Could not search with {0}: No search handler defined", key);
49                     return null;
50                 }
51                 return Handlers[key].SearchTransform(query);
52             } else {
53                 return null;
54             }
55         }
56     }
57 }