#!/usr/bin/python3

"""
@file
@copyright
  SPDX-FileCopyrightText: 2020-2025 European Southern Observatory (ESO) @n
  SPDX-License-Identifier: LGPL-3.0-only
"""

import elt.config
import elt.oldb
import sys
import argparse


def set_oldb_content(uri: str, content):
    oldb_client = elt.oldb.CiiOldbFactory.get_instance()
    oldb_value_dp = oldb_client.get_data_point(elt.config.Uri(uri))
    oldb_value_dp.write_value(content)


def parse_args(arguments):
    """
    Parses the command line arguments passed as a list
    If you pass the command line arguments, first remove argv[0]
    by passing:
        sys.argv[1:]
    """

    parser = argparse.ArgumentParser(
        description="""
Utility to be used in the definition of the actions
that will took place after stopping a nomad task.
In the current implementation is only ensures that the value of the 
given state attribute in the OLDB is set to Off.
"""
    )

    parser.add_argument(
        "-u",
        "--uri",
        required=True,
        type=str,
        help="Application state oldb uri that will be set to Off.",
    )

    # This contains the parsed arguments
    args = parser.parse_args(arguments)

    return args


def main(args):
    app_state_uri = args.uri
    if not "cii.oldb:///" in app_state_uri:
        app_state_uri = f"cii.oldb:///{app_state_uri}"
    print(f"App state uri {app_state_uri}")
    try:
        # Set app state to Off
        set_oldb_content(app_state_uri, "Off")
        return 0
    except Exception as ex: 
        print(ex)
        return 1   

if __name__ == "__main__":
    args = parse_args(sys.argv[1:])
    ISOK = main(args)

    sys.exit(ISOK)
