#    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.

# isitup.org domain lookup.
# --Kudu, Kays.

import urllib.request, urllib.parse, urllib.error, json

@plugin
class IsItUp(object):
    """Check domain status using isitup.org"""
    def __init__(self, server):
        self.server = server
        self.prnt = server.prnt
        self.commands = ["isitup"]
        self.server.handle("command", self.handle_command, self.commands)
    
    def handle_command(self, channel, user, cmd, args):
        if len(args) < 1:
            self.server.doMessage(channel, user+": Not enough arguments.")
            return

        if args[0].startswith("http://"):
            url = args[0][7:]
        elif args[0].startswith("https://"):
            url = args[0][8:]
        else:
            url = args[0]        
        code = "".join(x.decode('utf8') for x in urllib.request.urlopen("http://isitup.org/"+url+".json").readlines())
        #code = code.decode('utf8')
        print(code)
        arr = json.loads(code)
        arr['up'] = 'up' if arr['status_code'] == 1 else 'not up'
        if arr['up'] == 'up':self.server.doMessage(channel, user+': %(domain)s:%(port)s is %(up)s. Got HTTP status code %(response_code)03d from %(response_ip)s in %(response_time)f ms.' % arr)
        else: self.server.doMessage(channel, user+': %s is not up.' % arr['domain'])