#!/usr/bin/python
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
# Copyright (C) 2010-2014 Mathieu Comandon <strycore@gmail.com>
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, 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/>.

"""Program entry point"""

import os
import sys
import logging
import optparse
import signal

# pylint: disable=E0611
from gi.repository import Gtk, GObject

from os.path import realpath, dirname, normpath

LAUNCH_PATH = dirname(realpath(__file__))
if LAUNCH_PATH != "/usr/bin":
    SOURCE_PATH = normpath(os.path.join(LAUNCH_PATH, '..'))
    sys.path.insert(0, SOURCE_PATH)

from lutris.gui import dialogs

try:
    import yaml as _yaml  # noqa
except ImportError:
    q = dialogs.QuestionDialog({'title': "Dependency not available",
                                'question': "PythonYAML is not installed,\n"
                                            "do you want to install it now?"})
    if q.result == Gtk.ResponseType.YES:
        os.system('software-center python-yaml')
    else:
        sys.exit()

from lutris.util.log import logger
from lutris.installer import InstallerDialog
from lutris.config import check_config  # , register_handler
from lutris.game import Game
from lutris import pga
from lutris.gui.lutriswindow import LutrisWindow
from lutris.settings import VERSION, GAME_CONFIG_DIR


# Support for command line options.
parser = optparse.OptionParser(version="%prog " + VERSION)
parser.add_option("-v", "--verbose", action="store_true",
                  dest="verbose", help="Verbose output")
parser.add_option("-d", "--debug", action="store_true",
                  dest="debug", help="Show debug messages")
parser.add_option("-i", "--install", dest="installer_file",
                  help="Install a game from a yml file")
parser.add_option("-l", "--list-games", action="store_true",
                  help="List all games in database")
parser.add_option("-s", "--list-steam", action="store_true",
                  help="List Steam (Windows) games")
parser.add_option("--reinstall", action="store_true", help="Reinstall game")
(options, args) = parser.parse_args()

# Set the logging level to show debug messages.
console = logging.StreamHandler()
fmt = '%(levelname)-8s %(asctime)s [%(module)s]:%(message)s'
formatter = logging.Formatter(fmt)
console.setFormatter(formatter)
logger.addHandler(console)
logger.setLevel(logging.ERROR)

if options.verbose:
    logger.setLevel(logging.INFO)

if options.debug:
    logger.setLevel(logging.DEBUG)

if options.list_games:
    for game in pga.get_games():
        print u"{:<40} | {:<40} | {:<15} | {:<64}".format(
            game['name'][:40],
            game['slug'][:40],
            game['runner'],
            game['directory'] or '-'
        ).encode('utf-8')
    exit()
if options.list_steam:
    from lutris.runners import winesteam
    steam_runner = winesteam.winesteam()
    print steam_runner.get_appid_list()
    exit()


check_config(force_wipe=False)

installer = False
game = None

signal.signal(signal.SIGINT, signal.SIG_DFL)


game_slug = ""
for arg in args:
    if arg.startswith('lutris:'):
        game_slug = arg[7:]
        break

if game_slug or options.installer_file:
    file_path = os.path.join(GAME_CONFIG_DIR, game_slug + ".yml")
    db_game = pga.get_game_by_slug(game_slug) \
        or pga.get_game_by_slug(game_slug, field='installer_slug')
    if db_game and db_game['installed'] and not options.reinstall:
        logger.info("Launching %s", db_game['name'])
        lutris_game = Game(db_game['slug'])
        lutris_game.play()
    else:
        logger.info("Installing %s", game_slug)
        InstallerDialog(options.installer_file or game_slug)
        GObject.threads_init()
        Gtk.main()
else:
    logger.debug("Welcome to Lutris")
    LutrisWindow()
    GObject.threads_init()
    Gtk.main()
