#!/usr/bin/python3

"""
@file oldb-cli.py
@ingroup srv-oldb-python
@copyright (c) Copyright ESO 2024 All Rights Reserved

 ESO (eso.org) is an Intergovernmental organisation, and therefore special legal conditions apply.
"""

from argparse import ArgumentParser, ArgumentError
from contextlib import redirect_stderr
from elt.oldb.cli import cii_oldb_cli
from io import StringIO
import logging
from os.path import sep
from sys import argv, exit


TOOL_NAME = argv[0].split(sep)[-1]


SUCCESS_CODE = 0
INVALID_OPERATION_ERR_CODE = 1
OPERATION_FAILED_ERR_CODE = 2


def handle_read(args: list[str]):
    cii_oldb_cli.read(args)


def handle_write(args: list[str]):
    cii_oldb_cli.write(args)


def handle_subscribe(args: list[str]):
    cii_oldb_cli.subscribe(args)


def handle_create(args: list[str]):
    cii_oldb_cli.create(args)


def handle_delete(args: list[str]):
    cii_oldb_cli.delete(args)


OPERATION_HANDLERS = {
    "read": handle_read,
    "write": handle_write,
    "subscribe": handle_subscribe,
    "create": handle_create,
    "delete": handle_delete
}


def _main():
    parser = ArgumentParser(TOOL_NAME, exit_on_error=False)
    parser.add_argument('operation', help="Specifies the operation to perform (read, write, subscribe, create, delete).", choices=['read', 'write', 'subscribe', 'create', 'delete'])
    parser.add_argument('args', help="Arguments for the operation.", type=str, nargs='*')

    # msc 2024-02: ECII-948  patch:
    #   $ oldb-cli create -h
    #      causes this wrapper's help message to be output twice,
    #      while the operation handler's help is no longer shown.
    #      This is a quick fix (ignorant of the wrapper magic below).
    #
    # bypass the wrapper's argparser so it can't react to '-h'
    class FakeArgs:
       operation = None
       args = None
    if len(argv)>1 and argv[1] in OPERATION_HANDLERS:
        args = FakeArgs()
        args.operation = argv[1]
        args.args = argv[2:]
    else:
        args = parser.parse_args()

    #try:
    #    f = StringIO()
    #    with redirect_stderr(f):
    #        args = parser.parse_args()
    #except:
    #    parser.print_help()
    #    exit(INVALID_OPERATION_ERR_CODE)


    # NOTE(mdziezyc): sanity check
    if args.operation not in OPERATION_HANDLERS:
        logging.error("Invalid operation specified!")
        parser.print_help()
        exit(INVALID_OPERATION_ERR_CODE)

    # NOTE(mdziezyc): cii_oldb_cli raises custom exceptions on errors;
    # just pass the error code from it.
    try:
        OPERATION_HANDLERS[args.operation](args.args)
    except cii_oldb_cli.CiiCliException as e:
        logging.error(str(e))
        exit(e.get_code())

    exit(SUCCESS_CODE)


if __name__ == """__main__""":
    _main()
