"""
Save actuator references.
"""

import argparse
import subprocess
import sys
import time

import fastfbck
import fastfbck.backend as backend

from fastfbck import Destination
from fastfbck.dialog import DialogResult, NullDialog, ZenityDialog
from fastfbck.helpers import *

dialog = NullDialog()

def make_idx(act, npois):
    """
    S(H)XR act is a string like A1P1. Need to get the index from
    that string. Special case is A10
    """
    if act[2] == "0":
        idx = 9 * npois
    else:
        idx = act2idx(int(act[1])) * npois

    idx += poi2idx(int(act[-1]))

    return idx

def get_array(hxr, sxr):
    # Maximum size of the array is 40 - 10 actuators, 4 patterns.
    all_vals = [ 0 for _ in range(40) ]
    npois = 4
    for (hxr_act, hxr_val), (sxr_act, sxr_val) in zip(hxr.items(), sxr.items()):

        hxr_idx = make_idx(hxr_act, npois)
        sxr_idx = make_idx(sxr_act, npois)

        all_vals[hxr_idx] = hxr_val
        all_vals[sxr_idx] = sxr_val

    return all_vals


def get_act_refs(loop):
    refs_hxr = fastfbck.get_act_refs(loop, Destination.HXR)
    refs_sxr = fastfbck.get_act_refs(loop, Destination.SXR)

    return get_array(refs_hxr, refs_sxr)

def get_act_offsets(loop):
    offsets_hxr = fastfbck.get_act_offsets(loop, Destination.HXR)
    offsets_xxr = fastfbck.get_act_offsets(loop, Destination.SXR)

    return get_array(offsets_hxr, offsets_sxr)

def save_act_refs(loop, refs):
    backend.put_array(loop, "ACTREF", refs)

def save_act_offsets(loop, offsets):
    backend.put_array(loop, "ACTOFFSETS", offsets)

def main(loop):
    """ Save actuator references and offsets for both destinations """

    # Pop-up question on whether to save actuators or not
    title = "Save actuators?"
    msg = "Would you like to save current actuator references?"
    res = dialog.question(msg, title=title)

    if res != DialogResult.OK:
        print("Cancelling - did not save actuators.")
        sys.exit(0)

    try:
        print("Getting actuator refs...")
        refs = get_act_refs(loop)

    except backend.TimeoutError as e:
        msg = "Timeout when trying to save actuators."
        msg += f"\n{e}"
        msg += "\nActuators not saved!"
        dialog.error(msg)
        print(msg)
        sys.exit(0)

    try:
        print("Getting actuator offsets...")
        offsets = get_act_offsets(loop)

    except backend.TimeoutError as e:
        msg = "Timeout when trying to save offsets."
        msg += f"\n{e}"
        msg += "\nActuators not saved!"
        dialog.error(msg)
        print(msg)
        sys.exit(0)


    print("Saving...")
    save_act_refs(loop, refs)
    save_act_offsets(loop, offsets)

    print("Done.")

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

    parser = argparse.ArgumentParser(description=\
            "Save 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("-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()
    try:
        installed = backend.get(loop, "INSTALLED")
        if not installed:
            raise RuntimeError(f"{loop} not installed.")
    except backend.TimeoutError:
        raise ValueError(f"Invalid feedback loop. Check to ensure {loop} is" +
                "installed and running.")

    main(loop)

    time.sleep(0.5)
