using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;

public class HandController : MonoBehaviour 
{
	public const float ADDITIONAL_ROTATION = 180f;
	public const float ROTATION_DURATION = 0.7f;

	public Transform thumb, index, middle, ring, pinky;
	public float rotationDuration = 0.7f;

	protected HingeJoint[] thumbJoints;
	protected HingeJoint[] indexJoints;
	protected HingeJoint[] middleJoints;
	protected HingeJoint[] ringJoints;
	protected HingeJoint[] pinkyJoints;

	protected virtual void Awake()
	{
		thumbJoints = thumb.GetComponentsInChildren<HingeJoint>();
		indexJoints = index.GetComponentsInChildren<HingeJoint>();
		middleJoints = middle.GetComponentsInChildren<HingeJoint>();
		ringJoints = ring.GetComponentsInChildren<HingeJoint>();
		pinkyJoints = pinky.GetComponentsInChildren<HingeJoint>();
	}

	public void SetNormal(Vector3 normal, Vector3 indexDirection, float duration = ROTATION_DURATION)
	{
		Quaternion originalRotation = transform.rotation;
		Vector3 finalEulerAngles;

		indexDirection = indexDirection.normalized;
		normal = normal.normalized;

		if (Vector3.Dot(normal, indexDirection) != 0)
		{
			Debug.Log("Normal and index direction not perpendicular.");
			return;
		}

		transform.LookAt(transform.position + normal);
		transform.Rotate(0f, ADDITIONAL_ROTATION, 0f);

		if (indexDirection != Vector3.zero)
		{
			for (int i = 0; i < 10; i++)
			{
				if (transform.up != indexDirection)
					transform.Rotate(0f, 0f, 45f);
			}
		}

		finalEulerAngles = transform.eulerAngles;
		transform.rotation = originalRotation;
		transform.DORotate(finalEulerAngles, duration).SetEase(Ease.InOutQuad);

        AudioMaster.PlayGestureMoveClip();
	}

	protected void SetFingerState(HingeJoint[] fingerJoints, bool isUp)
	{
		for (int i = 0; i < fingerJoints.Length; i++)
		{
			fingerJoints[i].useMotor = !isUp;
		}
	}
}