from argparse import ArgumentParser, Namespace
from typing import Any, Callable, Optional, Sequence

from use_cx_oracle.business import execute_query_biz
from use_cx_oracle.storage.OracleDb import OracleDb


def get_description() -> str:
    return "use_cx_oracle instead of sqldeveloper or sqlplus"


def get_parser() -> ArgumentParser:
    parser = ArgumentParser(description=get_description())
    parser.add_argument(
        "-u",
        "--username",
        help="Username",
    )
    parser.add_argument(
        "-p",
        "--password",
        help="Password (pending secure replacement).",
    )
    parser.add_argument(
        "-o",
        "--host",
        help="Host",
    )
    parser.add_argument(
        "-q",
        "--query_file",
        help="Path to the sql query file.",
    )
    parser.add_argument(
        "-a",
        "--args_file",
        help="Path to the file containing the input args for the query.",
    )
    parser.add_argument("-r", "--port", help="Port", default="1521")
    parser.add_argument(
        "-s",
        "--sid",
        help="SID",
    )
    return parser


def print_out(foo):
    status = foo.status
    results = foo.results
    error = foo.error
    if error is not None:
        print(f"Error: {status} {error}")
    for row in results:
        print(f"{','.join(map(str,row))}")


def process_with_argparsed(
    args: Namespace, help_func: Callable, storage: Any = OracleDb()
) -> None:
    if (
        args.username
        and args.password
        and args.host
        and args.port
        and args.sid
        and (args.query_file or args.args_file)
    ):
        foo = execute_query_biz(
            args.username,
            args.password,
            args.host,
            args.port,
            args.sid,
            args.query_file,
            args.args_file,
            storage,
        )
        print_out(foo)
    else:
        help_func()


def client_parse_args(parser: ArgumentParser, args: Optional[Sequence[str]]) -> None:
    process_with_argparsed(
        parser.parse_args(args),
        parser.print_help,
    )


def get_preparsed_args(args: dict) -> Optional[Sequence[str]]:
    return args[1:]


def use_cx_oracle_cli_main(args: dict) -> None:
    client_parse_args(get_parser(), get_preparsed_args(args))
