#!/usr/bin/env python3
import sys
import os
import getopt
import shutil
from os.path import realpath, dirname, normpath

APPLICATION_NAME = "Minigalaxy"

LAUNCH_PATH = dirname(realpath(__file__))
if os.path.isdir(os.path.join(LAUNCH_PATH, "../minigalaxy")):
    SOURCE_PATH = normpath(os.path.join(LAUNCH_PATH, '..'))
    sys.path.insert(0, SOURCE_PATH)
    os.chdir(SOURCE_PATH)

from minigalaxy.version import VERSION
from minigalaxy.paths import CONFIG_DIR, CACHE_DIR


def usage():
    print("Usage:\t{} [OPTION]".format(sys.argv[0]))
    print("\nA simple GOG Linux client\n")
    print("Options:")

    print("\t-h, --help\t\tDisplay this help and exit")
    print("\t-v, --version\t\tDisplay version information and exit")
    print("\t--reset\t\t\tReset the configuration of Minigalaxy")


def parse_args():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hv", ["help", "version", "reset"])
    except getopt.GetoptError as err:
        # print help information and exit:
        print(err)  # will print something like "option -a not recognized"
        usage()
        sys.exit(2)
    for o, a in opts:
        if o in ("-v", "--version"):
            print(VERSION)
            sys.exit()
        elif o in ("-h", "--help"):
            usage()
            sys.exit()
        elif o == "--reset":
            shutil.rmtree(CONFIG_DIR, ignore_errors=True)
            shutil.rmtree(CACHE_DIR, ignore_errors=True)


def main():
    parse_args()

    # Import the gi module after parsing arguments
    from minigalaxy.ui.gtk import Gtk
    from minigalaxy.ui import Window

    # Start the application
    window = Window(APPLICATION_NAME)
    window.connect("destroy", Gtk.main_quit)
    Gtk.main()


if __name__ == "__main__":
    main()
