#!/usr/local/bin/python3.8
'''
Creates an instance of the program GUI and starts the main event loop.

@author: Peter Parente
@author: Eitan Isaacson
@organization: IBM Corporation
@copyright: Copyright (c) 2006 IBM Corporation
@license: BSD

All rights reserved. This program and the accompanying materials are made 
available under the terms of the BSD which accompanies this distribution, and 
is available at U{http://www.opensource.org/licenses/bsd-license.php}
'''
import gi
gi.require_version('Wnck', '3.0')

from gi.repository import GLib

import sys, os

def migrate_data (old_path, new_path):
  if os.path.exists(old_path) and not os.path.exists(new_path):
    mask = os.umask(0o77)
    try:
      os.renames(old_path, new_path)
    except:
      print("Unable to migrate ", old_path)
    os.umask(mask)

# Load gail module no matter what the desktop-wide settings are.
os.environ['GTK_MODULES'] = 'gail:atk-bridge'
# make the accerciser directory part of the path to aid user imports
sys.path.append(os.path.join(GLib.get_user_config_dir(), 'accerciser'))
# We can't rely on prefix if we're installed by relocated RPM. Instead, we 
# use __file__ and for now hope that lib is relative to bin.
sys.prefix = '/usr/local'
libs = os.path.join(sys.prefix, 'lib',
                    'python3.8', 'site-packages')
# point to the proper site-packages path
sys.path.insert(1, libs)

# TODO: Remove completely gnome dependency
# make this program accessible
#
#import gnome
## make this program accessible
#props = { gnome.PARAM_APP_DATADIR : os.path.join(sys.prefix, 'share')}
#gnome.program_init('accerciser', '3.38.0', 
#                   properties=props, argv=['accerciser'] + sys.argv[1:])

gi.require_version('Gtk', '3.0')
from gi.repository import Gtk as gtk
# initialize threads
# get global icon resources
it = gtk.IconTheme()
try:
  icons = [it.load_icon('accerciser', size, gtk.IconLookupFlags.NO_SVG) 
           for size in (16, 22, 32)]
except Exception:
  # ignore errors, and just don't use the icon
  pass
else:
  # TODO: REVIEW
  gtk.Window.set_default_icon_list(icons)

# Try migration
old_plugin_dir = os.path.join(os.environ['HOME'], '.accerciser', 'plugins')
new_plugin_dir = os.path.join(GLib.get_user_data_dir(), 'accerciser', 'plugins')
migrate_data(old_plugin_dir, new_plugin_dir)
old_bookmarks = os.path.join(os.environ['HOME'], '.accerciser', 'bookmarks.xml')
new_bookmarks = os.path.join(GLib.get_user_config_dir(), 'accerciser', 'bookmarks.xml')
migrate_data(old_bookmarks, new_bookmarks)
old_plugindata = os.path.join(os.environ['HOME'], '.accerciser', 'plugindata')
new_plugindata = os.path.join(GLib.get_user_data_dir(), 'accerciser', 'plugindata')


import accerciser
accerciser.main()
