using UnityEngine;
using System.Collections.Generic;

public class RigController : MonoBehaviour {
    private Dictionary<string, JointController> controlledJoints;
    public bool UpdateEnabled = true;

    protected virtual void Awake() {
        controlledJoints = new Dictionary<string, JointController>();
    }

    /// <summary>
    /// This method adds a joint to the controlled joints list so it updates every frame
    /// </summary>
    /// <param name="jointName">Name of the joint</param>
    /// <param name="code">Keycode</param>
    protected Transform AddJoint(string jointName, string inputAxis) {
        GameObject jointObject = gameObject.FindChildByName(jointName);
        
        // If the object cannot be found, show an impressive error
        if (jointObject == null) {
            Debug.LogError("ERROR: Joint '"+jointName+"' cannot be found!",this);
            return null; }

        // Try to get the component from the object
        JointController jointController = jointObject.GetComponent<JointController>();

        // If it doesn't have the JointController script yet, add it :)
        if (jointController == null) {
            jointController = jointObject.AddComponent<JointController>(); }
        
        // Add it to the array
        controlledJoints.Add(inputAxis,jointController);

        return jointController.transform;
    }

    private void Update() {
        foreach (KeyValuePair<string, JointController> pair in controlledJoints) {
            JointController controller = pair.Value;

            if (UpdateEnabled) {
                controller.UpdateTargetRotation(Input.GetAxisRaw(pair.Key));
            } else {
                controller.UpdateReset();
            }
        }
    }
}
