Added "search" architecture
[WebThing.git] / SearchHandler.cs
diff --git a/SearchHandler.cs b/SearchHandler.cs
new file mode 100644 (file)
index 0000000..54d5009
--- /dev/null
@@ -0,0 +1,57 @@
+using System;
+using System.Collections.Generic;
+using System.Text.RegularExpressions;
+
+namespace bytex64.WebThing {
+    public class SearchHandler {
+        WebThing wt;
+        Dictionary<string,ISearchPlugin> Handlers;
+        
+        public SearchHandler(WebThing wt) {
+            Handlers = new Dictionary<string,ISearchPlugin>();
+            this.wt = wt;
+
+            foreach (SearchHandlerPair p in Config.SearchHandlers) {
+                AddHandler(p.Shortcut, p.Plugin);
+            }
+        }
+
+        public void AddHandler(string key, string plugin) {
+            if (Handlers.ContainsKey(key)) {
+                Console.WriteLine("Cannot add search handler {0}: shortcut {1} already registered", plugin, key);
+                return;
+            }
+            if (!wt.Plugins.Plugins.ContainsKey(plugin)) {
+                Console.WriteLine("Cannot add search handler {0}: Plugin for {0} not loaded", plugin);
+                return;
+            }
+
+            WebThingPlugin p = wt.Plugins.Plugins[plugin];
+            Type ptype = p.GetType();
+
+            if (ptype.GetInterface("ISearchPlugin") != null) {
+                Handlers[key] = (ISearchPlugin) p;
+                Console.WriteLine("Added handler {0} for key {1}", plugin, key);
+            } else {
+                Console.WriteLine("Cannot add search handler {0}: {0} Does not implement ISearchPlugin", plugin);
+            }
+        }
+
+        // Call a search handler based on the leading word
+        public string Transform(string search) {
+            Regex get_handler_re = new Regex(@"^([\w-]+)\s+");
+            Match m = get_handler_re.Match(search);
+            if (m.Success) {
+                string key = m.Groups[1].Value;
+                string query = get_handler_re.Replace(search, "");
+                if (!Handlers.ContainsKey(key)) {
+                    Console.WriteLine("Could not search with {0}: No search handler defined", key);
+                    return null;
+                }
+                return Handlers[key].SearchTransform(query);
+            } else {
+                return null;
+            }
+        }
+    }
+}