# Copyright (c) 2017-2018 Cedric Bellegarde <cedric.bellegarde@adishatz.org>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gio, GLib, Gdk

from threading import current_thread
from signal import signal, SIGINT, SIGTERM

from passbook.application_actions import ApplicationActions
from passbook.settings import Settings
from passbook.helper_secrets import SecretsHelper


class Application(Gtk.Application, ApplicationActions):
    """
        Passbook application
    """

    def __init__(self, version):
        """
            Create application
            @param version as str
        """
        Gtk.Application.__init__(self)
        try:
            from pykeepass import PyKeePass
            PyKeePass
            self.keepass = True
        except:
            self.keepass = False
        self.__settings = Settings.new()
        ApplicationActions.__init__(self)
        self.__version = version
        self.__window = None
        self.debug = False
        self.__secret_service = None
        self.__icon_theme = Gtk.IconTheme.new()
        signal(SIGINT, lambda a, b: self.quit())
        signal(SIGTERM, lambda a, b: self.quit())
        self.add_main_option("debug", b"d", GLib.OptionFlags.NONE,
                             GLib.OptionArg.NONE, "Debug Passbook", None)
        self.add_main_option("version", b"v", GLib.OptionFlags.NONE,
                             GLib.OptionArg.NONE,
                             "Passbook version",
                             None)
        # Set main thread name
        # We force it to current python 3.6 name, to be sure in case of
        # change in python
        current_thread().setName("MainThread")
        GLib.set_application_name('Passbook')
        GLib.set_prgname('org.gnome.Passbook')
        self.connect("activate", self.__on_activate)
        self.connect("handle-local-options", self.__on_handle_local_options)
        self.connect("command-line", self.__on_command_line)
        self.register(None)
        if self.get_is_remote():
            Gdk.notify_startup_complete()

    def do_startup(self):
        """
            Init application
        """
        Gtk.Application.do_startup(self)
        self.__init()

    def quit(self, vacuum=False):
        """
            Quit application
            @param vacuum as bool
        """
        Gio.Application.quit(self)

    @property
    def settings(self):
        """
            Get settings
            @return Settings
        """
        return self.__settings

    @property
    def window(self):
        """
            Get window
            @return Window
        """
        return self.__window

    @property
    def secret_service(self):
        """
            Get secret service
            @return Secret.Service
        """
        return self.__secret_service

    @property
    def icon_theme(self):
        """
            Get icon_theme
            @return Gtk.IconTheme
        """
        return self.__icon_theme

    @property
    def css_provider(self):
        """
            Get default css provider
            @return Gtk.CssProvider
        """
        return self.__css_provider

#######################
# PRIVATE             #
#######################
    def __init(self):
        """
            Init main application
        """
        from passbook.window import Window
        # self.settings = Settings.new()
        cssProviderFile = Gio.File.new_for_uri(
            'resource:///org/gnome/Passbook/application.css')
        cssProvider = Gtk.CssProvider()
        cssProvider.load_from_file(cssProviderFile)
        self.__css_provider = Gtk.CssProvider()
        screen = Gdk.Screen.get_default()
        styleContext = Gtk.StyleContext()
        styleContext.add_provider_for_screen(screen, cssProvider,
                                             Gtk.STYLE_PROVIDER_PRIORITY_USER)
        styleContext.add_provider_for_screen(screen, self.__css_provider,
                                             Gtk.STYLE_PROVIDER_PRIORITY_USER)
        SecretsHelper.load_collections(self.__on_get_secret_service)
        self.__window = Window(self)
        self.__window.setup()
        self.__window.show()
        Gdk.notify_startup_complete()

    def __on_get_secret_service(self, service):
        """
            Set service
            @param service as Secret.Service
        """
        self.__secret_service = service

    def __on_handle_local_options(self, app, options):
        """
            Handle local options
            @param app as Gio.Application
            @param options as GLib.VariantDict
        """
        if options.contains("version"):
            print("Passbook", self.__version)
            exit(0)
        elif options.contains("debug"):
            self.debug = True
        return -1

    def __on_command_line(self, app, app_cmd_line):
        """
            Handle command line
            @param app as Gio.Application
            @param options as Gio.ApplicationCommandLine
        """
        if self.__window is None:
            from passbook.window import Window
            self.__window = Window()
        Gdk.notify_startup_complete()
        return 0

    def __on_activate(self, application):
        """
            Call default handler, raise last window
            @param application as Gio.Application
        """
        if self.__window:
            self.window.present()
