#! /usr/bin/env python
# -*- coding: utf-8 -*-

# glChess is a 2D/3D chess game for GNOME. This is the startup
# script which imports the relevant modules. Please keep the startup
# script in sync between glChess and gnome-sudoku.
#
# Copyright (c) 2008  You may use and distribute this
# software under the terms of the GNU General Public License, 
# version 2 or later.

import sys
import os

# Some version of PyGTK require this to be called before importing the gtk module
import pygtk
pygtk.require('2.0')

# Ignore any exceptions writing to stdout using print statements
class SafeStdout:
    def __init__(self):
        self.stdout = sys.stdout
    
    def fileno(self):
        return self.stdout.fileno()

    def write(self, data):
        try:
            self.stdout.write(data)
        except:
            pass
sys.stdout = SafeStdout()

# Setup bugbuddy to report unhandled exceptions.
try: 
    import bugbuddy
    bugbuddy.install('glchess')
except:
    #No bugbuddy support
    pass

def report_error():
    import os.path
    import gettext
    import traceback
    from gettext import gettext as _

    gettext.bindtextdomain('gnome-games', os.path.join('/usr/local', 'share', 'locale'))
    gettext.textdomain('gnome-games')
    # Translators: This is the title of the dialog displayed if glChess cannot start
    title = _("Chess incorrectly installed")
    # Translators: This is the contents of the dialog displayed if glChess cannot start
    description = _("""Chess is not able to start because required application files are not installed. If you are currently upgrading your system please wait until the upgrade has completed.""")

    traceback.print_exc()
    try:
        import gtk
    except ImportError:
        print title
        print '-' * len(title)
        print description
    else:
        dialog = gtk.MessageDialog(type = gtk.MESSAGE_ERROR, message_format = title)
        dialog.format_secondary_text(description)
        dialog.add_button(gtk.STOCK_QUIT, gtk.RESPONSE_CLOSE)
        dialog.run()
    sys.exit(0)

# Chek if we are installed
root_dir = os.path.dirname(__file__)
if os.path.exists(os.path.join(root_dir, 'Makefile.am')):
    sys.path.insert(0, os.path.abspath(root_dir))
    import lib
    sys.modules['glchess'] = sys.modules['lib']

try:
    # Import glChess from pyexecdir or system installation.
    from glchess.glchess import start_game
    start_game()
except ImportError:
    # Import of glChess failed. Show error message.
    report_error()

