# handles argument parsing + collecting inputs
import argon2
import argparse
from getpass import getpass
from . import input_manager
import os

def main():
    # all parsers
    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers(dest = "command")

    add_admin_parser = subparsers.add_parser("newadmin", help = "add a new admin user(creates new vault)")
    add_admin_parser.add_argument("--username", required=True)
    add_admin_parser.add_argument("--password")

    add_creds_parser = subparsers.add_parser("newcreds", help = "add new credentials for an application/website")
    add_creds_parser.add_argument("--site", required=True)
    add_creds_parser.add_argument("--username", required=True)
    add_creds_parser.add_argument("--password")

    del_parser = subparsers.add_parser("del", help ="delete a selected user credential")
    del_parser.add_argument("--entryID", required =True)

    update_parser = subparsers.add_parser("update", help = "update existing credentials for fields: password username site")
    update_parser.add_argument("--entryID", required=True)
    update_parser.add_argument("--field", required=True)
    update_parser.add_argument("--newinfo", required=True)

    list_parser = subparsers.add_parser("list", help="list all of the existing credentials")

    list_site_parser = subparsers.add_parser("sitelist", help ="list credentials belonging to a specified site")
    list_site_parser.add_argument("--site", required=True)

    view_parser = subparsers.add_parser("view", help = "view a specific password")
    view_parser.add_argument("--entryID", required = True)

    reset_parser = subparsers.add_parser("reset", help="WARNING: this will RESET the vault, deleting all credentials in the vault.")

    del_admin_parser = subparsers.add_parser("deladmin", help="WARNING: this will DELETE the admin account. Vault will no longer exist.")


    args = parser.parse_args()

    try:
        if args.command == "newadmin":
            if os.path.exists(f"{args.username}_vault.json") or os.path.exists(f"{args.username}.json"):
                confirm_overwrite = input(f"There already exists a vault under admin name: \n{args.username} \nDo you want to overwrite it? Y/N? ")
                if confirm_overwrite == "Y" or confirm_overwrite == "y":
                    if args.password is None:
                        args.password = getpass(f"Enter a password for {args.username}: ")
                    print("Creating new vault ...")
                    input_manager.add_admin(args.username, args.password)
                else:
                    print("New admin request cancelled. Consider choosing a different admin username.")
            else:
                if args.password is None:
                    args.password = getpass(f"Enter a password for {args.username}: ")
                print("Creating new vault ...")
                input_manager.add_admin(args.username, args.password)

            
        elif args.command == "newcreds":
            if args.password is None:
                args.password = getpass(f"Enter a password for the new entry: ")

            admin_username = input("Please enter the admin username: ")
            admin_password = getpass("Please enter the admin password: ")
            input_manager.add_creds(admin_username, admin_password, args.username, args.site, args.password)
            
        elif args.command == "del":
            # confirm and execute or cancel delete action
            admin_username = input("Please enter the admin username: ")
            admin_password = getpass("Please enter the admin password: ")
                
            confirm = input(f"Are you sure you want to delete entry {args.entryID}?\nThis action cannot be undone. Y/N? ")
            if confirm == "Y" or confirm == "y":
                input_manager.delete_creds(admin_username, admin_password, args.entryID)
            else:
                print("Delete request cancelled.")
            
        elif args.command == "update":
            # sanitize inputs
            whitelist = ["password", "username", "site"]
            while args.field not in whitelist:
                args.field = input("You've entered an invalid field.\nValid fields are: \npassword\nusername\nsite\nPlease enter a valid field: ")
            admin_username = input("Please enter the admin username: ")
            admin_password = getpass("Please enter the admin password: ")
            input_manager.update_creds(admin_username, admin_password, args.entryID, args.field, args.newinfo)
            
        elif args.command == "list":
            admin_username = input("Please enter the admin username: ")
            admin_password = getpass("Please enter the admin password: ")
            input_manager.list_all(admin_username, admin_password)
            
        elif args.command == "sitelist":
            admin_username = input("Please enter the admin username: ")
            admin_password = getpass("Please enter the admin password: ")
            input_manager.list_by_site(admin_username, admin_password, args.site)
            
        elif args.command == "view":
            admin_username = input("Please enter the admin username: ")
            admin_password = getpass("Please enter the admin password: ")
            input_manager.see_pwrd(admin_username, admin_password, args.entryID)
            
        elif args.command == "reset":
            admin_username = input("Please enter the admin username: ")
            admin_password = getpass("Please enter the admin password: ")
            confirm = input(f"Are you sure you want to reset the vault for Admin {admin_username}?\nThis action cannot be undone. Y/N? ")
            if confirm == "Y" or confirm == "y":
                input_manager.reset_DB(admin_username, admin_password)
            else:
                print("Reset request cancelled.")

        elif args.command == "deladmin":
            # first confirm and execute or cancel delete admin action
            admin_username = input("Please enter the admin username: ")
            admin_password = getpass("Please enter the admin password: ")
                
            confirm1 = input(f"Are you sure you want to delete {admin_username}'s vault?\nThis action cannot be undone. Y/N? ")
            if confirm1 == "Y" or confirm1 == "y":
                input_manager.delete_admin(admin_username, admin_password)
            else:
                print("Delete admin request cancelled.")        
        else:
            parser.print_help()
    except argon2.exceptions.VerifyMismatchError:
        print("Incorrect password entered.")
    except FileNotFoundError:
        print("The vault for the admin username does not exist.")
    except ValueError:
        print("Please be sure to enter integer values for entryID.")

if __name__ == "__main__":
    main()


    
