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

public class FindMyBones : MonoBehaviour
{
    [SerializeField] private Transform[] bonesToAttachTo;
    [SerializeField] private GameObject[] propsToUseAsBones;
    [SerializeField] private GooglyEyeAdder googlyEyeAdder;
    public UnityEvent onBonesFound;
    public UnityEvent onHideOrigianl;

    private bool runBonesFound; // field
    public bool RunBonesFound   // property
    {
        get { return runBonesFound; }   // get method
        set { runBonesFound = value; }  // set method
    }

    void Start()
    {
        onHideOrigianl?.Invoke();
        if (bonesToAttachTo.Length == 0) {
            Debug.LogError($"No bones to attach to {gameObject.name}");
        }
    }

    public void ConstructBones()
    {
        List<GameObject> garbages = new List<GameObject>(propsToUseAsBones);

        bool done = false;
        foreach (Transform child in bonesToAttachTo) {
            if (garbages.Count == 0) break;
            int index = Random.Range(0, garbages.Count);
            GameObject garbage = garbages[index];
            garbages.RemoveAt(index);
            garbage.transform.DORotateQuaternion(child.rotation, 5f).Play();
            garbage.transform.DOMove(child.position, 5f).Play().onComplete += () => { 
                garbage.transform.parent = child;
                garbage.transform.localPosition = Vector3.zero;
                garbage.transform.tag = "BodyShot";
                garbage.gameObject.layer = 7;//Enemy Layer
                googlyEyeAdder.AddEyes(garbage.GetComponent<MeshFilter>());
                if (done == false) {
                    done = true;
                    if (runBonesFound) {
                        onBonesFound.Invoke();
                    }
                }
            };
        }
    }

    public void DestopryBones()
    {
        StartCoroutine(DesotryAnimation());
    }

    IEnumerator DesotryAnimation()
    {
        foreach (GameObject prop in propsToUseAsBones)
        {
            prop.transform.parent = null;
        }

        yield return new WaitForSeconds(0.2f);
        foreach (GameObject prop in propsToUseAsBones)
        {
            yield return new WaitForSeconds(0.3f);
            FractureGeometry fracture = prop.GetComponent<FractureGeometry>();
            if (fracture != null) {
                try {
                    fracture.FractureAndForget();
                } catch (System.Exception e) {
                    Debug.Log(e);
                }
            }
        }
    }
}
