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

public class Pincher : MonoBehaviour
{
    public Transform left;
    public Transform right;
    public FixedJoint2D joint;
    public Transform pinchPoint;

    public Vector2 angleLimits;
    bool holding = false;
    public float value = 0;

    private void Awake() {
        SetPinchPercentage(0);
    }

    public void SetPinchPercentage(float v) {
        value = v;
        if (v > .8f) {
            v = 1f;
            if (!holding) {
                holding = true;

                Collider2D collider = Physics2D.OverlapCircle(pinchPoint.position, 0.1f);
                if (collider != null) {
                    Rigidbody2D rb = collider.attachedRigidbody;
                    if (rb != null) {
                        joint.connectedBody = rb;
                        joint.autoConfigureConnectedAnchor = true;
                        joint.enabled = true;

                        //Debug.Log($"Pinched: {rb}", rb);
                    }
                }
            }
        } else {
            holding = false;
            joint.enabled = false;
        }

        float angle = v.Map(0, 1, angleLimits.x, angleLimits.y);
        var rotLeft = Quaternion.Euler(0, 0, angle);
        var rotRight = Quaternion.Euler(0, 0, -angle);
        left.localRotation = rotLeft;
        right.localRotation = rotRight;


    }
}
