using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.UI;
using System.IO;

public class GestureManager : MonoBehaviour
{

	[DllImport("Motion_RecognizeHG")]
	public extern static void creatRecognizeHG();

	[DllImport("Motion_RecognizeHG")]
	public extern static OutPutGesture recognizeHG(float[] quaData);

	[DllImport("Motion_RecognizeHG")]
	public extern static void releaseRecognizeHG();



	public MotionInstance motionInstance;

	private float[] inputQuaData = new float[128];

	private OutPutGesture preGesture;

	private int updateCount = 0;

	public event Action<int, GestureType> gestureChangeEvent;


	public Text leftHandGesture_Text;
	public Text leftHandGestureProbability_Text;
	public Text rightHandGesture_Text;
	public Text rightHandGestureProbability_Text;


	// Start is called before the first frame update
	void Start()
	{
		Init();
	}


	private void Init()
	{
		creatRecognizeHG();

		preGesture.left_hand_label = -1;
		preGesture.left_hand_probability = 100;
		preGesture.right_hand_label = -1;
		preGesture.right_hand_probability = 100;
	}

	private void Update()
	{
		if (updateCount % 3 == 0)
		{
			UpDateGesture();
		}
		updateCount++;
	}

	/// <summary>
	/// 
	/// </summary>
	private void UpDateGesture()
	{
		inputQuaData = motionInstance.GetGloveData();
		OutPutGesture curGesture = recognizeHG(inputQuaData);
		Debug.Log(":" + curGesture.left_hand_label + "  :" + curGesture.left_hand_probability + "  :" + curGesture.right_hand_label + "  :" + curGesture.right_hand_probability);

		if (curGesture.left_hand_label >= 0)
		{
			if (curGesture.left_hand_label != preGesture.left_hand_label)
			{
				if (curGesture.left_hand_probability > 80)
				{
					gestureChangeEvent?.Invoke(1, (GestureType)Enum.Parse(typeof(GestureType), curGesture.left_hand_label.ToString()));
				}
			}
		}

		if (curGesture.right_hand_label >= 0)
		{
			if (curGesture.right_hand_label != preGesture.right_hand_label)
			{
				if (curGesture.right_hand_probability > 80)
				{
					gestureChangeEvent?.Invoke(2, (GestureType)Enum.Parse(typeof(GestureType), curGesture.right_hand_label.ToString()));
				}
			}
		}
		preGesture = curGesture;

		leftHandGesture_Text.text = ":" + curGesture.left_hand_label.ToString();
		leftHandGestureProbability_Text.text = "Ƹ:" + curGesture.left_hand_probability.ToString();
		rightHandGesture_Text.text = ":" + curGesture.right_hand_label.ToString();
		rightHandGestureProbability_Text.text = "Ƹ:" + curGesture.right_hand_probability.ToString();
	}


	public struct OutPutGesture
	{
		public int left_hand_label;//
		public double left_hand_probability;//Ƹ
		public int right_hand_label;//
		public double right_hand_probability;//Ƹ
	}


	//
	public enum GestureType
	{
		OpenHand = 0,//
		Grab = 1,//ȭ
		Point = 2,//
		Victory = 3,//Ү
		Pinch = 4,//
		Ok = 5//ok
	}


	private void OnDestroy()
	{
		releaseRecognizeHG();
	}
}
