#!/usr/bin/env python3
#
# -*- Mode: python; coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*-
#
# GNOME Activity Journal
#
# Copyright © 2009 Seif Lotfy <seif@lotfy.com>
# Copyright © 2010 Siegfried Gevatter <siegfried@gevatter.com>
# Copyright © 2010 Peter Lund <peterfirefly@gmail.com>
# Copyright © 2020 The GNOME Activity Journal developers
#
# 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
import os
import sys
import dbus
import gettext
import optparse
import signal
import warnings

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

RUN_DIR=None

def update_sys_path():
    global RUN_DIR

    # Where this file lives
    RUN_DIR = os.path.abspath(os.path.dirname(__file__))

    # If GNOME Activity Journal is installed system-wide, as indicated by
    # this file residing in $prefix/bin, we expect to find the remaining code
    # in $prefix/share/gnome-activity-journal/.
    if os.path.basename(RUN_DIR) == 'bin':
        sys.path.insert(0, os.path.join(os.path.dirname(RUN_DIR),
                                        'share/gnome-activity-journal'))

def check_zeitgeist_version():
    from src.external import CLIENT, CLIENT_VERSION

    if CLIENT_VERSION is None:
        print("Error: Cannot identify Zeitgeist client version. Exiting ...")
        sys.exit(1)
    elif CLIENT_VERSION < config.ZEITGEIST_REQUIRED_VERSION:
        print()
        print("Available Zeitgeist version : {}.{}.{}".format(*CLIENT_VERSION))
        print(" Required Zeitgeist version : {}.{}.{} or later".format(*config.ZEITGEIST_REQUIRED_VERSION))
        print()
        print("If you have installed zeitgeist version {}.{}.{} or later, ".format(*config.ZEITGEIST_REQUIRED_VERSION))
        print("run the following command ( as normal user ) to terminate ")
        print("the older running version.")
        print()
        print(" $ systemctl restart --user zeitgeist.service")
        print()
        print("Else, please try the following:")
        print()
        print(" 1. Upgrade the 'zeitgeist' package in your distribution.")
        print(" 2. Build and install the latest zeitgeist package from:")
        print()
        print("    https://gitlab.freedesktop.org/zeitgeist/zeitgeist")
        print()
        print("See the README.md file for more information.")
        sys.exit(1)
    else:
        print("Connected to Zeitgeist version {}.{}.{}".format(*CLIENT_VERSION))

def find_and_load_zeitgeist_module():
    # Check for critical modules from other repositories.
    # Support side-by-side or nested repositories during development.
    #
    # If zeitgeist is installed locally (with --prefix=<home>/.local) then Python
    # should have added ~/.local/lib/python<ver>/site-packages to the search path
    # automatically.  If it hasn't, then take a closer look at site.USER_SITE,
    # site.USER_BASE, and site.ENABLE_USER_SITE.
    try:
        # repo/module names
        other_repos = ['zeitgeist']

        # paths of potential repos next to us and below us
        repo_paths = ([os.path.join(RUN_DIR, '..', repo) for repo in other_repos] +
                      [os.path.join(RUN_DIR, '.' , repo) for repo in other_repos])

        # look for (and import) the needed modules
        from imp import load_module, find_module
        for module in other_repos:
            m = find_module(module, repo_paths + sys.path)
            print("Using the \"%s\" python module from %s" % (module, os.path.abspath(m[1])))
            load_module(module, *m)

    except ImportError as e:
        print("ERROR: %s." % e)
        print()
        print("The 'zeitgeist' python3 module was not found. Please install 'python3-zeitgeist' package.")
        print()
        print("See the README.md file for more information.")
        sys.exit(1)

update_sys_path()

# FixMe: remove once the deprecation warnings are fixed
with warnings.catch_warnings():
    warnings.simplefilter("ignore", category=DeprecationWarning)
    find_and_load_zeitgeist_module()

from src import config

# Import zeitgeist.datamodel before running gettext.install, so that it doesn't
# override the location we set (ie., "build/mo").
from zeitgeist import datamodel

gettext.bindtextdomain('gnome-activity-journal', config.GETTEXT_PATH)
gettext.textdomain('gnome-activity-journal')
gettext.install('gnome-activity-journal', config.GETTEXT_PATH)

try:
    check_zeitgeist_version()
except dbus.exceptions.DBusException as e:
    print("ERROR: %s." % e)
    print()
    print("Cannot connect to zeitgeist daemon. Please check if 'zeitgeist' package is installed.")
    print()
    print("See the README.md file for more information.")
    sys.exit(1)

from src.main import Application

if __name__ == "__main__":
    app = Application()
    signal.signal(signal.SIGINT, signal.SIG_DFL)
    app.run(sys.argv)
