
using System.Collections;
using UnityEngine;

public class ShipPartLogic : MonoBehaviour
{
    public int hp = 5;
    private bool Destroyed;
    private float MinSpeed = 4.5f;
    private float MaxSpeed = 5.5f;
    private float speed;
    private GameObject xdemonHead;
    private Vector3 directionVector;
    private Vector3 toDemonVector;
    private float distance;
    private float destroyDistance = 50.0f;

    private Coroutine cor1;


    public void TakeDamage(GameObject demonHead, GameObject player, LayerMask destroiedshippartslayer)
    {
        if (!Destroyed)
        {
            xdemonHead = demonHead;
            hp -= 1;
            Debug.Log(hp);

            if (hp <= 0)
            {
                Destroyed = true;

                gameObject.layer = Mathf.RoundToInt(Mathf.Log(destroiedshippartslayer.value, 2));

                StartCoroutine(player.GetComponent<PlayerMovement>().Falling());
                cor1 = StartCoroutine(Fly(demonHead));
            }
        }
    }

    IEnumerator Fly(GameObject demonHead)
    {
        speed = Random.Range(MinSpeed, MaxSpeed);

        toDemonVector = demonHead.GetComponent<Transform>().position - transform.position;
        distance = toDemonVector.magnitude;

        directionVector = toDemonVector.normalized;

        while (distance < destroyDistance)
        {
            transform.position += directionVector * Time.deltaTime * speed;

            toDemonVector = demonHead.GetComponent<Transform>().position - transform.position;
            distance = toDemonVector.magnitude;

            yield return null;
        }

        Destroy(gameObject);
    }

    void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag.Equals(xdemonHead.tag) == true)
        {



            xdemonHead.GetComponent<DemonHeadMovement>().OverRideSpeed(2);
            var tempCallForDemon = xdemonHead.GetComponent<DemonHeadMovement>().MyDemonParent;
            tempCallForDemon.GetComponent<DemonMovement>().OverrideRotationSpeed();

            Destroy(gameObject);
        }
    }

    private void OnDestroy()
    {
        if (cor1 != null) StopCoroutine(cor1);
    }

}
