#    guppy Copyright (C) 2010-2011 guppy team members.
#
#    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
#    This is free software, and you are welcome to redistribute it
#    under certain conditions; type `show c' for details.

import xml.etree.ElementTree
import urllib.request, urllib.parse

@plugin
class Wikipedia(object):
    def __init__(self, server):
        self.server = server
        self.commands = ["wp"]
        self.server.handle("command", self.handle_command, self.commands)
    
    def handle_command(self, channel, user, cmd, args):
        if cmd == "wp":
            if len(args) < 1: 
                self.server.doMessage(channel, user+": Not enough arguments.")
                return
            
            url = "http://en.wikipedia.org/w/api.php?action=opensearch&limit=3&namespace=0&format=xml&search="
            query = " ".join(args)
            search = url + urllib.parse.quote_plus(query, "/")
            
            try:
                # get the data
                data = urllib.request.urlopen(search).readlines()

                # parse the xml to a xpath tree
                xml_tree = xml.etree.ElementTree.fromstringlist(data)

                # get <Items> tags
                # the first element in xml_tree is a <QUERY> tag
                # we don't need that. We want the <SECTION> tag, which is the
                # second tag, hence the index of 1.
                xml_Items = list(xml_tree[1])

                # loop and grab all <Description> tags
                # and have an array to store the results
                results = []

                for item in xml_Items:
                    this = list(item)
                    results.append( this[1].text.strip('\n') + ' ' + this[2].text.strip('\n') )

                for result in results:
                    self.server.doMessage(channel, result)
            except Exception as e:
                pass