#!/usr/bin/env python
# -*- coding: utf-8 -*-

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import socket
import sys
import traceback
import urlparse
from wmconsole.version3.viewers import viewer_geodata
from wmconsole.version3.viewers import viewer_hoststat
from wmconsole.version3.viewers import viewer_kiwihost
from wmconsole.version3.viewers import viewer_kiwiurl
from wmconsole.version3.viewers import viewer_links
from wmconsole.version3.viewers import viewer_robotstxt
from wmconsole.version3.viewers import viewer_sitetree
from wmconsole.version3.viewers import viewer_urls


class HttpProcessor(BaseHTTPRequestHandler):
    html_redirect = """<html><head><meta http-equiv="refresh" content="0; url=$url"/></head><body></body></html>"""
    html_error = """<!DOCTYPE html><html lang="en"><head></head><body><pre>$content<pre></body></html>"""

    class Parameters:
        def __init__(self, qs):
            self.qs = qs

        def get(self, name, default=None, index=0):
            try:
                return self.qs[name][index]
            except:
                return default

    endpoints = {}

    def __init__(self, handlers, *args):
        global html_core_page

        for handler in handlers:
            self.endpoints[handler.path] = (handler.title, handler())

        BaseHTTPRequestHandler.__init__(self, *args)

    def get_viewers_content(self, url):
        viewers = ""
        for path in sorted(self.endpoints):
            viewers += ("""<li><a href="%s?q=%s">%s</a></li>""" % (path, url, self.endpoints[path][0]))
        return viewers

    def do_GET(self):
        path = self.path
        qs = {}
        if '?' in path:
            path, tmp = path.split('?', 1)
            qs = urlparse.parse_qs(tmp)

        if path == "/ping":
            self.send_response(200)
            self.send_header('content-type', 'text/html')
            self.end_headers()
            self.wfile.write("")
            return

        try:
            if path in self.endpoints:
                return self.endpoints[path][1].process(path, self.Parameters(qs), self)
        except Exception:
            self.send_response(200)
            self.send_header('content-type', 'text/html')
            self.end_headers()
            self.wfile.write(self.html_error.replace("$content", traceback.format_exc()))
            return

        self.send_response(200)
        self.send_header('content-type', 'text/html')
        self.end_headers()
        self.wfile.write(self.html_redirect.replace("$url", sorted(self.endpoints.keys())[0]))


class HTTPServerV6(HTTPServer):
    address_family = socket.AF_INET6


def main():
    port = 8150

    if len(sys.argv) > 1:
        port = int(sys.argv[1])

    print "Starting on port %d..." % port

    server = HTTPServerV6(("::", port), lambda *args: HttpProcessor([
        viewer_geodata.GeoDataViewer,
        viewer_hoststat.HostStatViewer,
        viewer_kiwihost.KiwiHostViewer,
        viewer_kiwiurl.KiwiUrlViewer,
        viewer_links.LinksViewer,
        viewer_robotstxt.RobotsTxtViewer,
        viewer_sitetree.SiteTreeViewer,
        viewer_urls.UrlsViewer
    ], *args))

    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print "Terminating..."

if __name__ == "__main__":
    main()
