#!/usr/bin/python3
import os
import sys
from PyQt5 import QtWidgets, QtCore, QtDBus

try:
    from .__id__ import ID
    from .backend import cli
    from .backend import database
    from .backend import daemon
    from .backend import config
except ImportError:
    from __id__ import ID
    from backend import cli
    from backend import database
    from backend import daemon
    from backend import config

PREFERENCES_FILE = os.path.expanduser(f"~/.config/{ID}/preferences.json")


class Main(QtCore.QObject):
    def __init__(self, parent):
        super().__init__()
        self.parent = parent
        self.preferences = database.Database(PREFERENCES_FILE)
        self.daemon = daemon.Main(self)
        self.config = config.Main(self)
        self.daemon.disconnect.connect(self.bluezDisconnect)
        self.config.disconnect.connect(self.bluezDisconnect)

    @QtCore.pyqtSlot(str)
    def bluezDisconnect(self, path):
        service = "org.bluez"
        if QtDBus.QDBusConnection.systemBus().interface().isServiceRegistered(service).value():
            interface = "org.bluez.Device1"
            bus = QtDBus.QDBusConnection.systemBus()
            dev = QtDBus.QDBusInterface(service, path, interface, bus)
            dev.asyncCall("Disconnect")

    @QtCore.pyqtSlot(dict)
    def cli(self, cmd):
        if "config" in cmd:
            if not self.config.isVisible():
                self.config.show()
                self.config.raise_()

        if "quit" in cmd:
            self.parent.quit()


def main(cmd=""):
    app = QtWidgets.QApplication(sys.argv)
    app.setQuitOnLastWindowClosed(False)
    cmd = cli.parse(cmd)
    widget = Main(app)
    widget.cli(cmd)
    widget.bus = cli.QDBusObject(parent=widget)
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()
