import logging
import os
import time
import bot
import argparse
import BotResources

# Jorn
#token = 'OTE1MDY0OTk2OTk0NjMzNzI5.YaWKsA.Y9yaCGg_VXRL_qQVbs05vo7gSAc'

# Greada
#token = 'NzU2MzI3MjcxNTk3NDczODYz.X2QOqQ.LVLj2b-RXQzPmhNuBC1eGFMcYls'

# Brent
#token = OTQzNzQyMDQwMjU1MTE1MzA0.Yg3eRA.ZxEbRr55xahjfaUmPY8pmS-RHTY

#name = "VoiceMeeter Output"

LOGGER = logging.getLogger("Discord_Radio_Bot.Main")


class BotDeviceNotFound(Exception):
    def __init__(self, device):
        LOGGER.debug(f"Unable to find the device: {device}")
        try:
           os.remove('./config.ini')
        except OSError:
            LOGGER.warning("Config file not found, restarting.")
            #os.execv(__file__, sys.argv)


def main(**passed_config):
    # Don't create a config if the user passed parameters
    if len(passed_config.keys()) == 0:
        LOGGER.info('Checking config file...')
        if not BotResources.check_if_config_exists():
            LOGGER.warning("No config file exists, please enter this information now")
            BotResources.write_config_file(init=True)

    config = BotResources.read_config_file()

    # Overwrite config options if they were passed
    if len(passed_config.keys()) == 0:
        for sub in config:
            # checking if key present in other dictionary
            if sub in passed_config and passed_config[sub]:
                config[sub] = passed_config[sub]

    LOGGER.info('Starting Bot...')

    discord_bot_client = bot.Bot(Token=config['Bot Token'], Device_ID=config['Device ID'],
                                 Device_Name=config['Device Name'], Mention_Group=config['Mention Group'],
                                 Channel_ID=config['Channel ID'], Handler=config['Handler'])

    LOGGER.debug(f"Verifying audio device:\t{config['Device Name']}")

    if not discord_bot_client.check_device(_override=bool("Device ID" in passed_config.keys())):
        raise BotDeviceNotFound(config['Device Name'])

    discord_bot_client.start_bot()


def cmd_arguments():
    parser = argparse.ArgumentParser(description='Discord Bot Gang - Premium Discord Bot\n'
                                                 'The more you listen, the less you can see')
    # Add the arguments

    # Arg to override bot token
    parser.add_argument('-t', '--token',
                        metavar='Bot Token',
                        dest='Bot Token',
                        type=str,
                        help='Override saved bot token')

    # Arg to override the input device in the config
    parser.add_argument('-i', '--input_device_id',
                        metavar='Device ID',
                        dest='Device ID',
                        type=int,
                        help='Override saved input device')

    # Arg to override mention group
    parser.add_argument('-m', '--mention',
                        metavar='Mention Group',
                        dest='Mention Group',
                        type=str,
                        help='Override saved mention group')

    # Arg to override default channel to send messages
    parser.add_argument('-c', '--channel',
                        metavar='Channel ID',
                        dest='Channel ID',
                        type=int,
                        help='Override saved sending channel')

    # Arg to override handler
    parser.add_argument('-u', '--handler',
                        metavar='Handler',
                        dest='Handler',
                        type=str,
                        help='Override saved SDR handler')

    # Arg to save the overridden arguments
    #parser.add_argument('-s', '--save',
    #                    metavar='save_overrides',
    #                    dest='save_overrides',
    #                    type=str,
    #                    help='Save the overridden arguments passed')

    # Retrieve the args
    args = vars(parser.parse_args())

    return args


if __name__ == '__main__':
    cmd_args = cmd_arguments()
    BotResources.init_global_logger()

    if not all(cmd_args.values()):
        LOGGER.debug("Passed arguments:")
        for arg in cmd_args:
            if cmd_args[arg]:
                LOGGER.debug(f"\t{arg}:\t{cmd_args[arg]}")

    try:
        LOGGER.info('Starting...')
        while True:
            try:
                main(**cmd_args)
            except BotDeviceNotFound:
                LOGGER.info("Restarting...")
                time.sleep(2)
    except KeyboardInterrupt:
        LOGGER.error("Exiting...")
