import BaseHTTPServer
import logging
import os
import pyqrcode
import socket
from socket import gethostname, gethostbyname
import time
import urlparse
import urllib
import webbrowser

from phone_sensor import SENSOR_PAGE_HTML


logger = logging.getLogger("pebble_tool.util.browser")

class BrowserController(object):
    def __init__(self):
        self.port = None

    def open_config_page(self, url, callback):
        self.port = port = self._choose_port()
        url = self.url_append_params(url, {'return_to': 'http://localhost:{}/close?'.format(port)})
        webbrowser.open_new(url)
        self.serve_page(port, callback)

    def serve_page(self, port, callback):
        # This is an array so AppConfigHandler doesn't create an instance variable when trying to set the state to False
        running = [True]

        class AppConfigHandler(BaseHTTPServer.BaseHTTPRequestHandler):
            def do_GET(self):
                path, query = self.path.split('?', 1)
                if path == '/close':
                    self.send_response(200)
                    self.end_headers()
                    self.wfile.write("OK")
                    running[0] = False
                    callback(query)
                else:
                    self.send_response(404)
                    self.end_headers()
                    self.wfile.write("Not Found")

        server = BaseHTTPServer.HTTPServer(('', port), AppConfigHandler)
        while running[0]:
            server.handle_request()

    def url_append_params(self, url, params):
        parsed = urlparse.urlparse(url, "http")
        query = parsed.query
        if parsed.query != '':
            query += '&'

        encoded_params = urllib.urlencode(params)
        query += encoded_params
        return urlparse.urlunparse((parsed.scheme, parsed.netloc, parsed.path, parsed.params, query, parsed.fragment))

    def serve_sensor_page(self, pypkjs_port, port=None):
        self.port = port = self._choose_port(port)
        pypkjs_port = [pypkjs_port]

        class SensorPageHandler(BaseHTTPServer.BaseHTTPRequestHandler):
            PERMITTED_PATHS = ['static/js/backbone-min.js',
                               'static/js/backbone-min.map',
                               'static/js/jquery-2.1.4.min.js',
                               'static/js/jQueryRotate.js',
                               'static/js/sensors.js',
                               'static/js/textdecoder.js',
                               'static/js/underscore-min.js',
                               'static/js/underscore-min.map',
                               'static/js/websocket.js',
                               'static/compass-rose.png',
                               'static/compass-needle.png',
                               'static/stylesheets/normalize.min.css',
                               'static/stylesheets/sensors.css']

            def do_HEAD(self):
                self.send_response(200)
                self.end_headers()

            def do_GET(self):
                requested_file = self.path.rsplit('/', 1)[1]
                file_path = self.path.lstrip('/')
                if requested_file == '':
                    self.send_response(200)
                    self.send_header('Content-type', 'text/html')
                    self.end_headers()
                    self.wfile.write(SENSOR_PAGE_HTML.format(websocket_host="'{}'".format(gethostbyname(gethostname())),
                                                             websocket_port="'{}'".format(pypkjs_port[0])))
                elif file_path in self.PERMITTED_PATHS:
                    try:
                        file_contents = open(os.path.join(os.path.dirname(os.path.realpath(__file__)), file_path))
                        self.send_response(200)
                        self.end_headers()
                        self.wfile.write(file_contents.read())
                    except IOError:
                        self.send_response(404)
                        self.end_headers()
                        self.wfile.write("Not Found")
                else:
                    self.send_response(403)
                    self.end_headers()
                    self.wfile.write("Forbidden")

            def log_request(self, code='-', size='-'):
                logger.debug("{} - - [{}] '{}' {} {}".format(self.client_address[0], self.log_date_time_string(),
                                                               self.requestline, code, size))

        server = BaseHTTPServer.HTTPServer(('', port), SensorPageHandler)
        url = "{}:{}".format(gethostbyname(gethostname()), server.server_port)
        url_code = pyqrcode.create(url)
        print(url_code.terminal(quiet_zone=1))
        print("=======================================================================================================")
        print("Please scan the QR code or enter the following URL in your mobile browser:\n{}".format(url))
        print("=======================================================================================================")
        print("\nUse Ctrl-C to stop sending sensor data to the emulator.\n")
        try:
            server.serve_forever()
        except KeyboardInterrupt:
            print("Stopping...")
            server.server_close()
            time.sleep(2) # Wait for WS connection to die between phone/QEMU

    def _choose_port(self, port=None):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind(('localhost', port or 0))
        addr, port = s.getsockname()
        s.close()
        return port

@@ -1958,33 +1958,34 @@
 elf.port = port 
-=
+or
  self._choose_po
@@ -1991,49 +1991,9 @@
 ort(
-port)%0A        pypkjs_port = %5Bpypkjs_port%5D
+)
 %0A%0A  
@@ -3518,19 +3518,16 @@
 kjs_port
-%5B0%5D
 )))%0A    
@@ -4517,24 +4517,29 @@
 Server(('', 
+self.
 port), Senso
@@ -5397,27 +5397,16 @@
 ort(self
-, port=None
 ):%0A     
@@ -5462,16 +5462,16 @@
 STREAM)%0A
+
         
@@ -5490,24 +5490,16 @@
 alhost',
- port or
  0))%0A   

Remove silly port selection