class Player(object):
    def __init__(self, stop_event):
        self.exceptions = (StoppedException, requests.exceptions.ConnectionError, socket.error,
                           websocket.WebSocketBadStatusException, websocket.WebSocketConnectionClosedException)
        self.stop_event = stop_event
        self.browser = None
        self.tab = None
        self.k = PyKeyboard()
        self.m = PyMouse()

    def connect(self):
        try:
            self.browser = Chromote(host="localhost", port=9222)
        except requests.exceptions.ConnectionError:
            self.browser = Chromote(host="localhost", port=9222, internet_explorer=True)
        kodi.log("connected to %s: %s" % (self.browser.browsertype, self.browser))

        while not self.stop_event.check():
            try:
                self.tab = next(tab for tab, title, url in self.browser.tabs if url != "about:blank" and "file://" not in url)
                break
            except StopIteration:
                xbmc.sleep(200)
        self.tab.connect_websocket()
        kodi.log("websocket connected: %s" % self.tab.url)

    def disconnect(self):
        if self.browser and self.browser.browsertype == "ie":
            self.browser.close_ieadapter()
            kodi.log("closed ieadapter")
        if self.tab:
            self.tab.close_websocket()

    def wait_for_new_episode(self, starting_urlid):
        starting_url = self.tab.url
        while not self.stop_event.is_set:
            try:
                xbmc.sleep(1000)
                current_url = self.tab.url
                if current_url == starting_url:
                    # no url change
                    continue
                is_episode_page = re.match(r".*www.netflix.com/watch/(\d+).*", current_url)
                if not is_episode_page:
                    continue
                new_urlid = is_episode_page.group(1)
                if new_urlid != starting_urlid:
                    # new episode started
                    return new_urlid
            except KeyError:
                # loading new page
                continue
            except self.exceptions:
                # browser closed
                return None

    def playpause(self):
        self.tab.get_element_by_class_name("player-play-pause").click()

    def next(self):
        self.tab.get_element_by_class_name("player-next-episode").click()

    def forward(self):
        self.k.tap_key(self.k.right_key)

    def rewind(self):
        self.k.tap_key(self.k.left_key)

    def cont(self):
        self.m.click(x=947, y=476)
        xbmc.sleep(100)
        self.m.move(**self.corner_coors)

    def stop(self):
        xbmc.Player().stop()
        self.stop_event.set()
class Player(object):
    def __init__(self):
        self.exceptions = (requests.exceptions.ConnectionError, socket.error,
                           websocket.WebSocketBadStatusException)
        self.tab = None
        self.stopped = False
        self.k = PyKeyboard()
        self.m = PyMouse()
        self.player_coord = None
        x, y = self.m.screen_size()
        self.corner_coord = {'x': x, 'y': y}
        self.middle_coord = {"x": x // 2, "y": y // 2}

    def connect(self):
        try:
            self.browser = Chromote(host="localhost", port=9222)
        except requests.exceptions.ConnectionError:
            self.browser = Chromote(host="localhost", port=9222, internet_explorer=True)
        kodi.log("connected to %s: %s" % (self.browser.browsertype, self.browser))

        while not self.stopped:
            try:
                self.tab = next(tab for tab, title, url in self.browser.tabs if url != "about:blank" and "file://" not in url)
                break
            except StopIteration:
                xbmc.sleep(50)
        self.tab.connect_websocket()
        kodi.log("websocket connected: %s" % self.tab.url)

    def cleanup(self):
        if self.browser.browsertype == "ie":
            self.browser.close_ieadapter()
            kodi.log("closed ieadapter")
        if self.tab:
            self.tab.close_websocket()

    def get_player_coord(self):
        playerelement = self.tab.get_element_by_id("playerelement")
        while not playerelement.present:
            xbmc.sleep(100)
        rect = playerelement.rect
        self.player_coord = {"x": int((rect["left"] + rect["right"]) / 2),
                             "y": int((rect["top"] + rect["bottom"]) / 2)}

    def wait_player_start(self):
        for _ in range(120):
            if "ProgressTracker" in self.tab.get_element_by_tag_name("script")["src"]:
                break
            xbmc.sleep(500)

    def wait_for_url_change(self, stored_url=None):
        stored_url = self.tab.url
        while True:
            try:
                current_url = self.tab.url
                if current_url != stored_url:
                    return current_url
            except KeyError:
                # loading new page
                continue
            except (requests.exceptions.ConnectionError, socket.error,
                    websocket.WebSocketBadStatusException):
                # browser closed
                return None
            xbmc.sleep(1000)

    def playpause(self):
        self.k.tap_key(self.k.up_key)
        self.k.tap_key(self.k.space_key)

    def forward(self):
        self.k.tap_key(self.k.right_key)

    def rewind(self):
        self.k.tap_key(self.k.left_key)

    def toggle_fullscreen(self):
        coord = self.player_coord if self.player_coord else self.middle_coord
        self.m.move(**coord)
        xbmc.sleep(200)
        self.m.click(n=2, **coord)
        self.m.move(**self.corner_coord)
        log.info("fullscreen toggled")

    def stop(self):
        xbmc.Player().stop()
        self.stopped = True