# dedicated to LC

from json import JSONDecoder
from urllib import urlencode
from urllib2 import urlopen

from karmabot.core.client import thing
from karmabot.core.commands.sets import CommandSet
from karmabot.core.register import facet_registry
from karmabot.core.thing import ThingFacet


@facet_registry.register
class LmgtfyFacet(ThingFacet):
    name = "lmgtfy"
    commands = thing.add_child(CommandSet(name))

    @classmethod
    def does_attach(cls, thing):
        return thing.name == "lmgtfy"

    @commands.add(u"lmgtfy {item}",
                  u"googles for a {item}")
    def lmgtfy(self, context, item):
        api_url = "http://ajax.googleapis.com/ajax/services/search/web?"
        response = urlopen(api_url + urlencode(dict(v="1.0",
                                                    q=item)))
        response = dict(JSONDecoder().decode(response.read()))
        top_result = {}
        if response.get('responseStatus') == 200:
            results = response.get('responseData').get('results')
            top_result = results.pop()
        context.reply(", ".join([top_result.get('titleNoFormatting'),
                                 top_result.get('unescapedUrl'),
                                 ]))

@@ -55,24 +55,33 @@
 rllib import
+ unquote,
  urlencode%0Af
@@ -79,16 +79,16 @@
 lencode%0A
-
 from url
@@ -292,16 +292,1007 @@
 gFacet%0A%0A
+import re%0Aimport htmlentitydefs%0A%0A##%0A# Function Placed in public domain by Fredrik Lundh%0A# http://effbot.org/zone/copyright.htm%0A# http://effbot.org/zone/re-sub.htm#unescape-html%0A# Removes HTML or XML character references and entities from a text string.%0A#%0A# @param text The HTML (or XML) source text.%0A# @return The plain text, as a Unicode string, if necessary.%0A%0A%0Adef unescape(text):%0A    def fixup(m):%0A        text = m.group(0)%0A        if text%5B:2%5D == %22&#%22:%0A            # character reference%0A            try:%0A                if text%5B:3%5D == %22&#x%22:%0A                    return unichr(int(text%5B3:-1%5D, 16))%0A                else:%0A                    return unichr(int(text%5B2:-1%5D))%0A            except ValueError:%0A                pass%0A        else:%0A            # named entity%0A            try:%0A                text = unichr(htmlentitydefs.name2codepoint%5Btext%5B1:-1%5D%5D)%0A            except KeyError:%0A                pass%0A        # leave as is%0A        return text%0A    return re.sub(%22&#?%5Cw+;%22, fixup, text)%0A%0A
 %0A@facet_
@@ -2051,16 +2051,17 @@
 lts.pop(
+0
 )%0A      
@@ -2087,16 +2087,25 @@
 %22.join(%5B
+unescape(
 top_resu
@@ -2131,16 +2131,17 @@
 atting')
+)
 ,%0A      

fix unichr escaping