#!/usr/bin/python3
# coding: utf-8
"""
 Just Another Desktop Environment
 Copyright (c) 2020 Vitor Lopes
 https://github.com/codesardine/Jadesktop

"""
import sys
import json
import Jade.Dbus
from dbus.mainloop.glib import DBusGMainLoop
from gi.repository import GLib
from gi.repository import Gio
import Jade.Icons as icons
from Jade.Utils import Session, Desktop
from JAK import Application
from JAK import IPC, WebEngine
from Jade.DropEvent import event
from JAK.Utils import bindings
from JAK.Utils import Instance
if bindings() == "PyQt5":
    from PyQt5.QtCore import Qt, pyqtSlot as Slot, QObject, pyqtProperty as Property
else:
    from PySide2.QtCore import Qt, Slot, QObject, Property 

Instance.auto("desktop", Desktop())
WebEngine.JWebView.dropEvent = event


class Bind:

    @staticmethod
    def get_desktop_app(file):
        desktop_file = Gio.DesktopAppInfo.new_from_filename(file)
        Gio.DesktopAppInfo.launch(desktop_file)


    @staticmethod
    def listen(data):
        if data.endswith(".desktop"):
            Bind.get_desktop_app(data)


class SharedObj(QObject):
    def __init__(self):
        super().__init__()

    @Slot()
    def showInspector(self):
        window = Instance.retrieve("win")
        window.showInspector()

    @Slot()
    def setBackgroundImage(self):
        desktop = Instance.retrieve("desktop")
        desktop.setBackground()

    @Slot()
    def hideInspector(self):
        window = Instance.retrieve("win")
        window.hideInspector()

    @Slot()
    def toggleDesktop(self):
        desktop = Instance.retrieve("desktop")
        desktop.toggle()

    @Slot(str)
    def setBranch(self, branch):
        desktop = Instance.retrieve("desktop")
        desktop.setBranch(branch)

    @Slot(bool)
    def setPanelVisible(self, value):
        desktop = Instance.retrieve("desktop")
        desktop.setPanelVisible(value)

    @Slot()
    def restoreDefaults(self):
        Desktop.restoreDefaultsDialog()

    @Slot()
    def updateMenu(self):
        Desktop.updateMenu()

    @Property(str)
    def about(self):
        return Desktop.about()

    @Slot(str, str)
    def saveSettings(self, key, value):
        Desktop.saveSettings(key, value)

    """ Icons """

    @Property(str)
    def icons(self):
        return json.dumps({
            "background": f"{icons.get('desktop')}",
            "restore": f"{icons.get('backup')}",
            "arrow-up": f"{icons.get('arrow-up')}",
            "arrow-down": f"{icons.get('arrow-down')}",
            "search": f"{icons.get('search-icon')}"
        })

    @Property(str)
    def getBranch(self):
        return Desktop.getBranch()



class Exit():

    @staticmethod
    def logOut(self):
        Session.logOut()

    @staticmethod
    def powerOff(self):
        Session.powerOff()

    @staticmethod
    def reboot(self):
        Session.reboot()

    @staticmethod
    def suspend(self):
        Session.suspend()


def main():

    if "--profile" in sys.argv:
        setFlags = (Qt.NoDropShadowWindowHint | Qt.WindowStaysOnBottomHint)
        setAttribute = ""
    else:
        setFlags = (Qt.NoDropShadowWindowHint | Qt.WindowStaysOnBottomHint | Qt.FramelessWindowHint)
        setAttribute = (Qt.WA_X11NetWmWindowTypeDesktop, Qt.WA_X11NetWmWindowTypeDesktop)

    app = Application.JWebApp(
        window = {
            "title": "JADE",
            "setFlags": setFlags,
            "fullScreen": True,
            "setAttribute": setAttribute,
            "transparent": True,
            "backgroundImage": Desktop.getBackground()
        },
        webview = {
            "webContents": f"{Desktop.getPath()}/themes/default/main.html",
            "webChannel": { "active": True, "sharedOBJ": SharedObj() },
            "injectJavaScript": {"JavaScript": Desktop.getJS(), "name": "JADE"},
            "addCSS": Session.userCSS()
        })
    app.run()


if __name__ == "__main__":
    DBusGMainLoop(set_as_default=True)
    loop = GLib.MainLoop()
    Jade.Dbus.Service()
    IPC.Bind = Bind
    if "--profile" in sys.argv:
        import cProfile
        cProfile.run("main()")
    else:
        main()
    loop.start()
