#!/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)
#     dd-mmm-yyyy, F. Lastname  (user)
#         Comment
#
# ==============================================================
#
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_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')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-a', '--area', help='Check out magnets in specified area')
group.add_argument('-e', '--element', help='Check out specified element')
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')
if len(sys.argv) == 1:
    parser.print_help()
    parser.exit()

args = parser.parse_args()

# Get matching magnets
utilities.init(args.facility)
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)
else:
    matching_magnets = utilities.get_all_magnets()

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

PreCheckoutRoutine.magnets = matching_magnets

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

# 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, magnet)
    checkout_data.load_json(json_file)

    # Run tests
    checkout_structure = AutoCheckoutStructure()
    for test in checkout_structure.test_iter():
        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)
