import asyncio
import logging
import sys
import threading
import traceback

from seleniumwire.thirdparty.mitmproxy import (
    addonmanager,
    command,
    controller,
    eventsequence,
    http,
    log,
    options,
    websocket,
)
from seleniumwire.thirdparty.mitmproxy.coretypes import basethread
from seleniumwire.thirdparty.mitmproxy.net import server_spec

from . import ctx as mitmproxy_ctx

# Conclusively preventing cross-thread races on mitmproxy shutdown turns out to be
# very hard. We could build a thread sync infrastructure for this, or we could
# wait until we ditch threads and move all the protocols into the async loop.
# Until then, silence non-critical errors.
logging.getLogger('asyncio').setLevel(logging.CRITICAL)


class ServerThread(basethread.BaseThread):
    def __init__(self, server):
        self.server = server
        address = getattr(self.server, "address", None)
        super().__init__("ServerThread ({})".format(repr(address)))

    def run(self):
        self.server.serve_forever()


class Master:
    """
    The master handles mitmproxy's main event loop.
    """

    def __init__(self, event_loop, opts):
        self.should_exit = threading.Event()
        self.channel = controller.Channel(
            self,
            event_loop,
            self.should_exit,
        )

        self.options: options.Options = opts or options.Options()
        self.commands = command.CommandManager(self)
        self.addons = addonmanager.AddonManager(self)
        self._server = None
        self.waiting_flows = []
        self.log = log.Log(self)

        mitmproxy_ctx.master = self
        mitmproxy_ctx.log = self.log
        mitmproxy_ctx.options = self.options

    @property
    def server(self):
        return self._server

    @server.setter
    def server(self, server):
        server.set_channel(self.channel)
        self._server = server

    def start(self):
        self.should_exit.clear()
        if self.server:
            ServerThread(self.server).start()

    async def running(self):
        self.addons.trigger("running")

    def run_loop(self, loop):
        self.start()
        asyncio.ensure_future(self.running())

        exc = None
        try:
            loop.run_forever()
        except Exception:  # pragma: no cover
            exc = traceback.format_exc()
        finally:
            if not self.should_exit.is_set():  # pragma: no cover
                self.shutdown()
            if not loop.is_closed():
                tasks = asyncio.all_tasks(loop) if sys.version_info >= (3, 7) else asyncio.Task.all_tasks(loop)
                for p in tasks:
                    p.cancel()
                loop.close()

        if exc:  # pragma: no cover
            print(exc, file=sys.stderr)

        self.addons.trigger("done")

    async def _shutdown(self):
        self.should_exit.set()
        if self.server:
            self.server.shutdown()
        loop = asyncio.get_event_loop()
        loop.stop()

    def shutdown(self):
        """
        Shut down the mitmproxy. This method is thread-safe.
        """
        if not self.should_exit.is_set():
            self.should_exit.set()
            ret = asyncio.run_coroutine_threadsafe(self._shutdown(), loop=self.channel.loop)
            # Weird band-aid to make sure that self._shutdown() is actually executed,
            # which otherwise hangs the process as the mitmproxy server is threaded.
            # This all needs to be simplified when the mitmproxy server runs on asyncio as well.
            if not self.channel.loop.is_running():  # pragma: no cover
                try:
                    self.channel.loop.run_until_complete(asyncio.wrap_future(ret))
                except RuntimeError:
                    pass  # Event loop stopped before Future completed.

    def _change_reverse_host(self, f):
        """
        When we load flows in reverse mitmproxy mode, we adjust the target host to
        the reverse mitmproxy destination for all flows we load. This makes it very
        easy to replay saved flows against a different host.
        """
        if self.options.mode.startswith("reverse:"):
            _, upstream_spec = server_spec.parse_with_mode(self.options.mode)
            f.request.host, f.request.port = upstream_spec.address
            f.request.scheme = upstream_spec.scheme

    async def load_flow(self, f):
        """
        Loads a flow and links websocket & handshake flows
        """

        if isinstance(f, http.HTTPFlow):
            self._change_reverse_host(f)
            if 'websocket' in f.metadata:
                self.waiting_flows.append(f)

        if isinstance(f, websocket.WebSocketFlow):
            hfs = [hf for hf in self.waiting_flows if hf.id == f.metadata['websocket_handshake']]
            if hfs:
                hf = hfs[0]
                f.handshake_flow = hf
                self.waiting_flows.remove(hf)
                self._change_reverse_host(f.handshake_flow)
            else:
                # this will fail - but at least it will load the remaining flows
                f.handshake_flow = http.HTTPFlow(None, None)

        f.reply = controller.DummyReply()
        for e, o in eventsequence.iterate(f):
            await self.addons.handle_lifecycle(e, o)
