using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class BodyPart : MonoBehaviour
{
    public float maxDistance = 1;
    public Vector2 input;

    Rigidbody2D rb;
    //RelativeJoint2D joint;
    SpringJoint2D[] joints;
    //TargetJoint2D joint;
    Vector2[] startOffsets;
    Vector2 startLocalPos;

    private void Awake() {
        rb = GetComponent<Rigidbody2D>();
        joints = GetComponents<SpringJoint2D>();
        startOffsets = new Vector2[joints.Length];
        for (int i = 0; i < joints.Length; i++) {
            startOffsets[i] = joints[i].connectedAnchor;
        }

        startLocalPos = transform.localPosition;
    }

    public void StartGrab() {
        Debug.Log("Grab");
    }

    public void StopGrab() {
        Debug.Log("Release");
    }

    // relative joints
    //private void FixedUpdate() {
    //    for (int i = 0; i < joints.Length; i++) {
    //        Vector2 targetPointWorld = (Vector2)transform.parent.TransformPoint(startOffsets[i]) + input* maxDistance;
    //        Vector2 targetLocalPoint = transform.parent.InverseTransformPoint(targetPointWorld);
    //        joints[i].linearOffset = -targetLocalPoint;

        
    //    }
    //}

    //Spring joints multiple, almost usable
    private void FixedUpdate() {
        for (int i = 0; i < joints.Length; i++) {
            Vector2 targetPointWorld = (Vector2)transform.parent.TransformPoint(startOffsets[i]) + input * maxDistance;
            Vector2 targetLocalPoint = transform.parent.InverseTransformPoint(targetPointWorld);
            joints[i].connectedAnchor = targetLocalPoint;


        }
    }

    // RelativeJoint2D
    //private void FixedUpdate() {
    //    Vector2 targetPointWorld = (Vector2)transform.parent.TransformPoint(startOffset) + input * maxDistance;
    //    Vector2 targetLocalPoint = transform.parent.InverseTransformPoint(targetPointWorld);
    //    joint.linearOffset = -targetLocalPoint;
    //}

    [ContextMenu("Reset Joints")]
    public void ResetJoints() {
        const float DIST_MULTI = 5f;
        const float CLOSE_DIST = 0.2f;
        joints = GetComponents<SpringJoint2D>();
        joints[0].anchor = new Vector2(CLOSE_DIST, 0f);
        joints[1].anchor = new Vector2(-CLOSE_DIST, 0f);
        joints[2].anchor = new Vector2(0f,CLOSE_DIST);
        joints[3].anchor = new Vector2(0f,-CLOSE_DIST);
        for (int i = 0; i < joints.Length; i++) {
            float fullDist = CLOSE_DIST * DIST_MULTI;
            joints[i].connectedAnchor = (Vector2)transform.localPosition + joints[i].anchor * DIST_MULTI;
            joints[i].distance = fullDist - CLOSE_DIST;
        }
    }

    private void OnDrawGizmos() {
        Gizmos.color = Color.yellow;
        Vector3 pos = startLocalPos;
        if (!Application.isPlaying)
            pos = transform.localPosition;

        Gizmos.DrawWireSphere(transform.parent.TransformPoint(pos), maxDistance);
    }
}