from string import Template
import urllib2
import wmconsole.version3.protos.geodata_pb2 as geodata_pb2
import html_main


class GeoDataViewer:
    title = "Geodata"
    path = "/geodata"

    html_nav = """
            <form class="navbar-form navbar-left" action="/geodata" 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">
                    <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>
    """

    html_body = """
            <div class="container">
                <div class="panel panel-default">
                    <div class="panel-body">
                    <pre>$proto</pre>
                    </div>
                </div>
            </div>
    """

    def get_content(self, url):
        content = ""

        # request = urllib2.Request(url="http://localhost:25020/getGeoData", )
        # request = urllib2.Request(url="http://webmaster-geodata.search.yandex.net:25020/getGeoData",)
        # request = urllib2.Request(url="http://webmaster.dev.search.yandex.net:25020/getGeoData",)
        request = urllib2.Request(url="http://webmaster-geo.n.yandex.ru/getGeoData",)
        response = urllib2.urlopen(request, url)
        content = response.read()

        obj = geodata_pb2.GeoDataMessage()
        obj.ParseFromString(content)
        content = str(obj)

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

    def process(self, path, qs, request):
        body_content = ""
        url = qs.get("q", "")

        try:
            if len(url) > 0:
                body_content = self.get_content(url)
        except IOError as e:
            body_content = "<pre>" + str(e) + "</pre>"

        nav = Template(self.html_nav).substitute(url=url)
        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)
