#!/usr/bin/env python

import argparse
import os
import sys
import logging
import meshroom
from localfarm.localFarmLauncher import FarmLauncher


parser = argparse.ArgumentParser(description="Launch or query local farm.")

parser.add_argument("-v", "--verbose",
                    help="Set the verbosity level for logging:\n"
                            "  - fatal: Show only critical errors.\n"
                            "  - error: Show errors only.\n"
                            "  - warning: Show warnings and errors.\n"
                            "  - info: Show standard informational messages.\n"
                            "  - debug: Show detailed debug information.\n"
                            "  - trace: Show all messages, including trace-level details.",
                    default=os.environ.get("MESHROOM_VERBOSE", "error"),
                    choices=["fatal", "error", "warning", "info", "debug", "trace"])

parser.add_argument(
    "-r", "--root", type=str, help="Local farm root folder.")

# Modes
subparsers    = parser.add_subparsers(dest="command")
start_mode    = subparsers.add_parser("start", help="Start the local farm.")
stop_mode     = subparsers.add_parser("stop", help="Stop the local farm.")
restart_mode  = subparsers.add_parser("restart", help="Restart the local farm.")
status_mode   = subparsers.add_parser("status", help="Check the farm status.")
fullinfo_mode = subparsers.add_parser("fullinfo", help="Display all info on the local farm.")


def start(args):
    root = args.root or None
    launcher = FarmLauncher(root=root)
    launcher.start()

def stop(args):
    root = args.root or None
    launcher = FarmLauncher(root=root)
    launcher.stop()

def restart(args):
    root = args.root or None
    launcher = FarmLauncher(root=root)
    launcher.restart()

def status(args):
    root = args.root or None
    launcher = FarmLauncher(root=root)
    launcher.status()

def fullinfo(args):
    root = args.root or None
    launcher = FarmLauncher(root=root)
    launcher.status(allInfo=True)


if __name__ == "__main__":
    args = parser.parse_args()
    logging.getLogger().setLevel(meshroom.logStringToPython[args.verbose])
    
    if args.command == "start":
        start(args)
    elif args.command == "stop":
        stop(args)
    elif args.command == "restart":
        restart(args)
    elif args.command == "status":
        status(args)
    elif args.command == "fullinfo":
        fullinfo(args)
    else:
        parser.print_help()
        sys.exit(0)
