from string import Template
import datetime
import json
import re
import urllib2
import html_main


class UrlsViewer:
    proxies = ["webmaster-urls.search.yandex.net:25040", "sas1-5600.search.yandex.net:12420", "webmaster.dev.search.yandex.net:25040"]

    path = "/urls"
    title = "Urls"

    html_nav = """
            <form class="navbar-form navbar-left" action="/urls" role="search">
                <div class="input-group navbar-searchbox">
                    <input type="text" name="q" class="form-control" value="$url" placeholder="http://site.ru" style="width:400px">
                    <input type="hidden" name="p" value="$proxy_name">
                    <span class="input-group-btn">
                        <button type="submit" class="btn btn-primary"><span class="glyphicon glyphicon-search" style="width:40px"></span></button>
                    </span>
                </div>
            </form>

            <ul class="nav navbar-nav navbar-right">
                <li class="dropdown">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">$proxy_name<span class="caret"></span></a>
                    <ul class="dropdown-menu" role="menu">
                        $proxy_list
                    </ul>
                </li>
            </ul>
    """

    html_body = """
        <div class="container-fluid" style="border-bottom:1px solid #e7e7e7; padding-bottom:16px">
            $meta
        </div>
        <br/>
        <div class="container">
            <div style="width:400px; margin:0 auto">
                $links
            </div>
        </div>
    """

    html_links = """
        <div class="panel panel-default panel-primary">
            <div class="panel-heading">Download</div>
            <ul class="list-group">
                $proto
            </ul>
        </div>
    """

    def get_object(self, url):
        try:
            request = urllib2.Request(url=url)
            response = urllib2.urlopen(request)
            content = response.read()
            obj = json.loads(content)
            return obj
        except IOError as e:
            print e
            return None

    def get_links(self, url, proxy):
        objects = self.get_object("http://%s/getUrlsMeta?host=%s" % (proxy, url))
        total_size = 0
        content = ""

        if objects is None:
            return "<h4>Not found</h4>"

        for obj in objects:
            meta = {}
            for code in obj:
                if code.startswith("."):
                    meta[code] = obj[code]
                    continue

                size = int(obj[code])

                if code != "samples":
                    total_size = total_size + size

                content = content + '<a href="/urls?q=%s&c=%s&p=%s" class="list-group-item"><span class="badge">%.2fmb</span><b>%s</b></a>' % (url, code, proxy, (size / 1048576), code)

        content += '<a href="/urls?q=%s&c=all&p=%s" class="list-group-item"><span class="badge">%.2fmb</span><b>All</b></a>' % (url, proxy, total_size / 1048576)
        content += '<h4>'

        for obj in meta:
            content += '<span class="label label-primary" style="margin: 5px">' + obj + " " + str(meta[obj]) + '</span>'

        content += "</h4>"

        return self.html_links.replace("$proto", content)

    def proxy_content(self, request, proxy, url, req_code):
        if req_code == "samples":
            link = "http://%s/getUrlsSamples?host=%s" % (proxy, url)
        elif req_code == "all":
            link = "http://%s/getUrlsUnauth?host=%s" % (proxy, url)
        else:
            link = "http://%s/getUrlsUnauth?host=%s&code=%s" % (proxy, url, req_code)

        try:
            req = urllib2.Request(url=link)
            response = urllib2.urlopen(req)

            request.send_response(200)
            request.send_header("Content-Description", "File Transfer")
            request.send_header("Content-Type", "application/octet-stream")
            request.send_header("Content-Disposition", "attachment; filename=%s.%s.tsv.gz" % (url.replace("://", "_"), req_code))
            request.send_header("Content-Transfer-Encoding", "binary")
            request.send_header("Expires", 0)
            request.send_header("Cache-Control", "must-revalidate")
            request.send_header("Pragma", "public")
            request.end_headers()

            while True:
                chunk = response.read(8192)
                if not chunk:
                    break

                request.wfile.write(chunk)

            return True
        except:
            pass

        return False

    def get_cache_content(self, proxy):
        cache_content = ""
        objs = self.get_object("http://%s/getUrlsCacheInfo" % proxy)

        for obj in objs:
            for ts in obj:
                text = ts
                match = re.search("(\\d+)", ts)
                if match:
                    text = ts + " | " + str(datetime.datetime.fromtimestamp(int(match.groups()[0])))
                cache_content += '<h4><span class="label label-primary"> %s </span></h4> ' % text

        return cache_content

    def process(self, path, qs, request):
        url = qs.get("q", "")
        proxy = qs.get("p", "")
        req_code = qs.get("c", "")

        if proxy not in self.proxies:
            proxy = self.proxies[0]

        if req_code and url:
            if self.proxy_content(request, proxy, url, req_code):
                return

        body_content = ""
        proxies_content = ""
        links_content = ""
        cache_content = ""

        if url:
            links_content = self.get_links(url, proxy)

        for addr in self.proxies:
            proxies_content += ("""<li><a href="/urls?&q=%s&p=%s">%s</a></li>""" % (url, addr, addr))

        cache_content = self.get_cache_content(proxy)

        body_content = Template(self.html_body).substitute(meta=cache_content, links=links_content)
        nav = Template(self.html_nav).substitute(url=url, proxy_name=proxy, proxy_list=proxies_content)
        answer = Template(html_main.html_core_page).substitute(title=self.title, nav=nav, viewers=request.get_viewers_content(url), body=body_content)

        request.send_response(200)
        request.send_header('content-type', 'text/html')
        request.end_headers()
        request.wfile.write(answer)
