#!/usr/bin/env python3

# ========================= #
# CLI TOOL                  #
# ========================= #

from argparse import ArgumentParser
from gpip import get, __version__

# ========================= #
# GET COMMAND               #
# ========================= #

def get_command(*args,**kwargs):
    get(
        *args,
        **kwargs
    )

# ========================= #
# INSTALL COMMAND           #
# ========================= #

def read_file(path: str) -> list:
    repositories = list()
    with open(path,'r') as fp:
        out = fp.readlines()
        fp.close()
    for x in out:
        repositories.append(x.replace('\n',''))
    return repositories

def install_command(*args,**kwargs):
    
    if len(args) > 1:
        print("Cannot install more than one file.")
        exit(1)

    repositories = read_file(args[0])

    if len(repositories) == 0:
        print("Empty file.")
        exit(1)

    get_command(
        *repositories
        ,**kwargs
    )

if __name__ == "__main__":

    COMMANDS = {
        "get": get_command,
        "install": install_command,
    }

    parser = ArgumentParser()
    
    # ========================= #
    # NEW #
    # ========================= #

    parser.add_argument(
        'action'
        ,choices=['get', 'install', 'help', 'version']
        ,help="the action to invoke with %(prog)s"
    )

    parser.add_argument(
        'arguments'
        ,nargs="*"
    )

    parser.add_argument(
        '--debug'
        ,required=False
        ,action="store_true"
        ,help="Enable debug mode."
    )

    get_group = parser.add_argument_group('GET')

    get_group.add_argument(
        '--https'
        ,required=False
        ,action="store_true"
        ,help="Enable HTTPS Mode."
    )

    get_group.add_argument(
        '--token'
        ,required=False
        ,type=str
        ,help="Provide token for https."
    )

    get_group.add_argument(
        '--upgrade'
        ,required=False
        ,action="store_true"
        ,help="Upgrade package."
    )

    get_group.add_argument(
        '--force'
        ,required=False
        ,action="store_true"
        ,help="Force install."
    )

    args = parser.parse_args()

    if "help" in args.action:
        parser.print_help()
        exit(0)

    if "version" in args.action:
        print("Currently installed version: {}".format(__version__))
        exit(0)

    COMMANDS[args.action](
        *args.arguments
        ,https=args.https
        ,token=args.token
        ,upgrade=args.upgrade
        ,force=args.force
        ,debug=args.debug
    )