2 using System.Collections.Generic;
3 using System.Text.RegularExpressions;
5 namespace bytex64.WebThing {
6 public class SearchHandler {
8 Dictionary<string,ISearchPlugin> Handlers;
9 ISearchPlugin DefaultSearchHandler;
11 public SearchHandler(WebThing wt) {
12 Handlers = new Dictionary<string,ISearchPlugin>();
15 foreach (SearchHandlerPair p in Config.SearchHandlers) {
16 AddHandler(p.Shortcut, p.Plugin);
18 if (Config.DefaultSearchHandler != null) {
19 SetDefaultHandler(Config.DefaultSearchHandler);
23 private bool IsValidSearchHandler(WebThingPlugin p) {
24 Type ptype = p.GetType();
25 if (ptype.GetInterface("ISearchPlugin") != null)
30 public void AddHandler(string key, string plugin) {
31 if (Handlers.ContainsKey(key)) {
32 Console.WriteLine("Cannot add search handler {0}: shortcut {1} already registered", plugin, key);
35 if (!wt.Plugins.Plugins.ContainsKey(plugin)) {
36 Console.WriteLine("Cannot add search handler {0}: Plugin for {0} not loaded", plugin);
40 WebThingPlugin p = wt.Plugins.Plugins[plugin];
42 if (IsValidSearchHandler(p)) {
43 Handlers[key] = (ISearchPlugin) p;
44 Console.WriteLine("Added handler {0} for key {1}", plugin, key);
46 Console.WriteLine("Cannot add search handler {0}: {0} Does not implement ISearchPlugin", plugin);
50 public void SetDefaultHandler(string plugin) {
51 if (wt.Plugins.Plugins.ContainsKey(plugin)) {
52 WebThingPlugin p = wt.Plugins.Plugins[plugin];
53 if (IsValidSearchHandler(p)) {
54 DefaultSearchHandler = (ISearchPlugin) p;
56 Console.WriteLine("Could not set default search handler: {0} does not implement ISearchPlugin", plugin);
59 Console.WriteLine("Could not set default search handler: {0} is not loaded", plugin);
63 // Call a search handler based on the leading word
64 public string Transform(string search) {
65 Regex get_handler_re = new Regex(@"^([\w-]+)\s+");
66 Match m = get_handler_re.Match(search);
68 string key = m.Groups[1].Value;
69 string query = get_handler_re.Replace(search, "");
70 if (Handlers.ContainsKey(key)) {
71 return Handlers[key].SearchTransform(query);
73 if (DefaultSearchHandler != null) {
74 return DefaultSearchHandler.SearchTransform(search);
76 Console.WriteLine("Could not search with {0} and no default search handler defined", key);
81 if (DefaultSearchHandler != null) {
82 return DefaultSearchHandler.SearchTransform(search);
84 Console.WriteLine("Could not get search key and no default search handler defined");