"""
fbckrestoreacts2

A rewrite of the fbckrestoreacts script which is destination-aware using the
fastfbck library
"""
import argparse
import enum
import sys
import time

import fastfbck
import fastfbck.backend as backend
from fastfbck import Destination
from fastfbck.dialog import DialogResult, NullDialog, ZenityDialog
from fastfbck.state import FeedbackState, get_loop_state
from fastfbck.backend.types import NamedEnum

# If this was imported into, say, a unit testing session use a NullDialog
dialog = NullDialog()

class RestoreSource(NamedEnum):
    AUTO   = enum.auto()
    MANUAL = enum.auto()
    TIME   = enum.auto()

def get_acts_by_time(loop, dest):
    """ Implement the old Fix the 6x6 functionality. """
    raise NotImplemented

def get_saved_acts(loop, dest, restore_src):
    """ Collect the saved actuator values and offsets by restore_src """
    saved_offsets = saved_refs = None
    if restore_src == RestoreSource.AUTO:
        saved_offsets = fastfbck.get_autosaved_act_offsets(loop, dest)
        saved_refs    = fastfbck.get_autosaved_act_refs(loop, dest)

    elif restore_src == RestoreSource.MANUAL:
        saved_offsets   = fastfbck.get_saved_act_offsets(loop, dest)
        saved_refs      = fastfbck.get_saved_act_refs(loop, dest)

    elif restore_src == RestoreSource.TIME:
        saved_offsets, saved_refs = get_acts_by_time(loop, dest)

    if not saved_offsets or not saved_refs:
        raise RuntimeError("Failed to get saved offsets or refs.")
    return ( saved_offsets, saved_refs )

def main(loop, dest, restore_src):
    """
    The main script.

    main collects saved actuators/offsets, turns off the feedback loop
    (if not already stopped), resets the actuator values, and restarts the loop
    (if necessary).
    """
    saved_offsets, saved_values = get_saved_acts(loop, dest, restore_src)
    if not saved_offsets or not saved_values:
        dialog.error("Quitting due to error when collecting actuators.")
        sys.exit(1)

    # Make sure the user *really* wants to reset the actuators.
    title = "Are you sure you want to restore actuators?"
    msg   = f"Restore actuators from {restore_src}?"
    res = dialog.question(msg, title=title)
    if res != DialogResult.OK:
        print("Cancelling - No change to actuators.")
        sys.exit(0)

    # Turn the feedback loop off if not already.
    initial_state = fastfbck.get_loop_state(loop).state
    fastfbck.set_loop_state(loop, FeedbackState.OFF)

    fastfbck.write_acts(loop, destination, saved_values)
    fastfbck.write_offsets(loop, destination, saved_offsets)

    # If feedback was on, turn it back on again.
    fastfbck.set_loop_state(loop, initial_state)

    print("Actuators restored")

if __name__ == "__main__":
    # Replace the NullDialog with a ZenityDialog
    dialog = ZenityDialog()

    # Set up the command line then pass control to the main script
    parser = argparse.ArgumentParser(description=\
            "Restore feedback actuator settings")
    parser.add_argument("-loop",
            metavar="FeedbackID",
            required=True,
            help="The name of the feedback loop. e.g. FB04:LG01",
            dest="fbloop")
    parser.add_argument("-destination",
            metavar="BeamDestination",
            required=True,
            help="Beam destination. HXR or SXR",
            dest="dest")
    parser.add_argument("-src",
            metavar="RestoreSource",
            required=True,
            help="Source to restore from (MANUAL or AUTO)",
            dest="src")
    parser.add_argument("-sim",
            metavar="Simulate",
            type=bool,
            help="Simulate the effect? Simulate = Do not write to the network",
            default=False,
            dest="simulate")

    args = parser.parse_args()

    if args.simulate:
        print("Setting up simulated backend")
        backend.ctx = backend.nowrite

    # TODO (rreno): validate the loop name
    loop = args.fbloop.upper()

    # Validate the destination
    try:
        destination = Destination[ args.dest.upper() ]
    except KeyError:
        parser.print_help()
        print(f"Invalid destination - {args.dest}")
        sys.exit(2)

    # Validate restore source
    # should be one of auto, manual, time
    try:
        restore_src = RestoreSource[ args.src.upper() ]
    except KeyError:
        parser.print_help()
        print(f"Invalid restore source - {args.src}")
        sys.exit(2)

    main(loop, destination, restore_src)

    time.sleep(0.5)
