#!/usr/bin/env python3
"""
Frank Hrach
BooruGet
"""


import argparse
import threading
import os

import DownloadManager
from arguments import arguments
from Gelbooru import GelbooruDownloader
from Danbooru import DanbooruDownloader


# file names
CONFIG = os.path.join(".config", "BooruGet.config")

def init_directories(additional_dir_name, out_dir):
    """
    Checks to see if the directories used by the program exist, and creates
    them if they do not
    """
    if not os.path.exists(out_dir):
        os.mkdir(out_dir)

    if not additional_dir_name == "" and \
        not os.path.exists(os.path.join(out_dir, additional_dir_name)):
        os.mkdir(os.path.join(out_dir, additional_dir_name))

def load_config_file():
    """
    Loads settings from the config file. Creates a blank config file if it
    does not exist already
    """
    global arguments
    global CONFIG

    if not os.path.exists(".config"):
        os.mkdir(".config")

    valid_settings = {"username": None, "apikey": None, "out_dir": "src"}

    # if the config file does not exist, create it
    if not os.path.exists(CONFIG):
        f = open(CONFIG, "w")
        f.write('username:\n')
        f.write('apikey:\n')
        f.write('out_dir:')
        f.close()

    f = open(CONFIG, "r")
    try:
        for line in f:
            current = line.strip().split(":")
            valid_settings[current[0]] = current[1]
    except:
        #this is most likely not a problem
        pass
    return valid_settings


def handle_arguments(arg):
    """
    Handles the command line arguments for the program

    arguments -> a dictionary containg any arguments from the config file

    returns -> the dictionary provided updated with the command arguments
    """

    parser = argparse.ArgumentParser()
    parser.add_argument(
        "-a", "--anysize", help="Allow any sized image. " +
        "Default is to only allow images equal to or larger than the " +
        "specified screen size", action="store_true")
    parser.add_argument(
        "-u", "--username", default=arg["username"],
        help="The username you use to log into danbooru this overrides what " +
        "is found in the config file if specified")
    parser.add_argument(
        "-k", "--apikey", default=arg["apikey"],
        help="Your api key can be found on your user page. This overrides " +
        "what is found in the config file if specified")
    parser.add_argument(
        "-w", "--width", help="the width of your screen in pixels", default=-1,
        type=int)
    parser.add_argument(
        "-t", "--height", help="the height of your screen in pixels",
        default=-1, type=int)
    parser.add_argument(
        "-e", "--error", help="the percentage error allowed for the image." +
        "Default is 5 percent", default=0.05, type=float)
    parser.add_argument(
        "-v", "--verbose", help="prints debug output", action="store_true")
    parser.add_argument(
        "--nsfw", help="Allow nsfw results, default is disallow",
        action="store_true")
    parser.add_argument(
        "--nodan", help="Do not download from danbooru", action="store_true")
    parser.add_argument(
        "--nogel", help="Do not download from gelbooru",
        action="store_true")
    parser.add_argument(
        "search", help="the string to search for. It is the exact same " +
        "string that would be entered into the site")

    return dict(list(arg.items()) +
        list(vars(parser.parse_args()).items()))


def main():
    """
    The entry point for the program
    """
    arg = load_config_file()
    arg = handle_arguments(arg)

    if arg['height'] == -1 and arg['width'] == -1:
        arg['anysize'] = True

    args = arguments(arg['anysize'], arg['height'], \
           arg['width'], arg['error'], arg['verbose'], \
           arg['nsfw'], arg['search'], arg['username'], \
           arg['apikey'])

    init_directories(arg['search'], arg['out_dir'])

    try:
        threads = []
        event = threading.Event()
        dl_manager = DownloadManager.DownloadManager(event, arg['out_dir'])
        threads.append(dl_manager)

        if not arg['nogel']:
            gel = GelbooruDownloader(args, dl_manager)
            threads.append(gel)
        if not arg['nodan']:
            dan = DanbooruDownloader(args, dl_manager)
            threads.append(dan)

        # Start all threads
        print("Starting downloads")
        for thread in threads:
            thread.start()

        # remove the download thread
        dl_thread = threads.pop(0)

        # Wait for all threads to finish
        for thread in threads:
            thread.join()

        print("Main thread done")

        if arg['verbose']:
            print("Sending shutdown message to download process")

        dl_manager.should_run = False
        dl_thread.join()


    except (KeyboardInterrupt, SystemExit):
        dl_manager.should_run = False
        raise

# Entry Point
main()
