#!/usr/bin/python3
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
#
# 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/>.

import os
import sys
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.application import Application

app = Application()
sys.exit(app.run(sys.argv))


if game_slug or installer:
    if not game_slug and not os.path.isfile(installer):
        print("No such file: %s" % installer)
        exit()

    db_game = None
    if game_slug:
        db_game = (pga.get_game_by_field(game_slug, 'id')
                   or pga.get_game_by_field(game_slug, 'slug')
                   or pga.get_game_by_field(game_slug, 'installer_slug'))

    runtime_updater = RuntimeUpdater()

    if db_game and db_game['installed'] and not options.reinstall:
        logger.info("Launching %s", db_game['name'])
        if lutris.is_running():
            lutris.run_game(db_game['id'])
        else:
            runtime_updater.update()
            lutris_game = Game(db_game['id'])
            lutris_game.exit_main_loop = True
            lutris_game.play()
            try:
                GLib.MainLoop().run()
            except KeyboardInterrupt:
                lutris_game.stop()
    else:
        logger.info("Installing %s", game_slug)
        if lutris.is_running():
            lutris.install_game(installer or game_slug)
        else:
            runtime_updater.update()
            InstallerDialog(installer or game_slug)
    exit()

