import os
import xbmc
import urllib2
import threading
from quasar.config import QUASARD_HOST
from quasar.daemon import shutdown


class QuasarMonitor(xbmc.Monitor):
    def __init__(self):
        self._closing = threading.Event()

    @property
    def closing(self):
        return self._closing

    def onAbortRequested(self):
        # Only when closing Kodi
        if xbmc.abortRequested:
            xbmc.executebuiltin("Dialog.Close(all, true)")
            shutdown()
            try:
                self._closing.set()
                self._closing.clear()
            except SystemExit as e:
                if e.code != 0:
                    os._exit(0)
                pass

    def onSettingsChanged(self):
        try:
            urllib2.urlopen("%s/reload" % QUASARD_HOST)
        except:
            pass
