#!/usr/bin/env python
# ==============================================================
#
#  Abs:   Script for automated checkout of magnets
#
#  Name:  mgnt_auto_checkout.py
#
#  Usage: mgnt_auto_checkout.py [-h] [-f FACILITY]
#                               (-a AREA | -e ELEMENT | -d DEVICE) [-n]
#
#  Facility: SLAC Controls (Development)
#
#  Auth:  08-Nov-2021, A. Le    (anle)
# --------------------------------------------------------------
#  Mods: (Latest to oldest)
#     09-May-2022, A. Le        (anle)
#         Show message when running ACSW power test
#     06-May-2022, A. Le        (anle)
#         Add option to run ACSW power test only
#     02-May-2022, A. Le        (anle)
#         Add option to redo failed checks
#     21-Mar-2022, A. Le        (anle)
#         Add option to perform only read-only checks
#         Add read-only field to all tests
#         Add option to write output to local directory
#
# ==============================================================
#
import argparse
import sys

import helpers.mgnt_utilities as utilities
from mgnt_auto_checkout_data import AutoCheckoutData
from mgnt_auto_checkout_structure import AutoCheckoutStructure
from tests.mgnt_general_acsw_power_test import GeneralACSWPowerTest
from tests.mgnt_multi_magnet_checkout_test import MultiMagnetCheckoutTest
from tests.mgnt_pre_checkout_routine import PreCheckoutRoutine

# Parse arguments
parser = argparse.ArgumentParser(description='Perform automated checkout of magnets')
parser.add_argument('-f', '--facility', help='Check out magnets in specified facility')
magnet_group = parser.add_mutually_exclusive_group(required=True)
magnet_group.add_argument('-a', '--area', help='Check out magnets in specified area')
magnet_group.add_argument('-e', '--element', help='Check out specified element')
magnet_group.add_argument('-d', '--device', help='Check out magnets by device name (* and ? allowed)')
parser.add_argument('-n', '--no-caput', action='store_true', help='Disable writing to production PVs')
parser.add_argument('-r', '--read-only', action='store_true', help='Perform only read-only checks (implies --no-caput)')
parser.add_argument('-j', '--json-dir',
                    help='Write JSON output to directory (default: $MGNT_REPORT/data in specified facility)')
parser.add_argument('-rf', '--redo-failed', action='store_true', help='Redo checks that failed on the previous run')
test_group = parser.add_mutually_exclusive_group()
test_group.add_argument('-t', '--test-id', help='Run a single test by id')
test_group.add_argument('-A', '--acsw', help='Run power test for a single ACSW')
if len(sys.argv) == 1:
    parser.print_help()
    parser.exit()

args = parser.parse_args()

# Get matching magnets
utilities.init(args.facility, args.json_dir)
if args.area:
    matching_magnets = utilities.get_magnets_by('area', args.area)
elif args.element:
    matching_magnets = utilities.get_magnets_by('element', args.element)
elif args.device:
    matching_magnets = utilities.get_magnets_by('device', args.device, wildcard=True)
elif args.acsw:
    matching_magnets = utilities.get_magnets_by('acsw_host', args.acsw)
else:
    matching_magnets = utilities.get_all_magnets()

if not matching_magnets:
    raise ValueError('No matching magnets found')

PreCheckoutRoutine.magnets = matching_magnets
MultiMagnetCheckoutTest.magnets = matching_magnets

# Disable caput if needed
if args.no_caput or args.read_only:
    utilities.enable_writes = False
    if args.read_only:
        utilities.read_only = True

# If ACSW is provided, run power test
if args.acsw:
    test = GeneralACSWPowerTest()
    print 'Running {} ({})'.format(type(test).__name__, test.description)
    test.execute(args.acsw)

else:
    # Perform tests
    for magnet in matching_magnets:
        print 'Checking out', magnet['element']
        # Clear previous test results
        utilities.results = {}

        # Load json data
        json_file = '{}.json'.format(magnet['element'])
        checkout_data = AutoCheckoutData(args.facility, args.json_dir, magnet)
        checkout_data.load_json(json_file)

        # Run tests
        checkout_structure = AutoCheckoutStructure()
        for test in checkout_structure.test_iter(args.test_id):
            prev_result = checkout_data.get_latest_result(test.test_id)
            if prev_result and prev_result['status'] and args.redo_failed:
                # Skip test if it passed and we are in redo-failed mode
                print 'Skipping {} ({}) since it already passed'.format(type(test).__name__, test.description)
                test.load_results(prev_result)
                utilities.results[test.test_id] = test
                continue

            elif args.read_only and not test.read_only:
                # Skip test if in read-only mode
                print 'Skipping {} ({})'.format(type(test).__name__, test.description)

            else:
                print 'Running {} ({})'.format(type(test).__name__, test.description)
                test.execute(magnet)
                utilities.results[test.test_id] = test

            # Update json data
            checkout_data.update(test)

        # Write back json data
        checkout_data.save_json(json_file)
