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

public class BreakableItem : MonoBehaviour
{
    public float BreakingForce = 10;
    private float CurrentBreakingForce = 10;

    [Header("Damage")]
    public float DamageScoreMin = 10;
    public float DamageScoreMax = 40;
    [Header("Breakage")]
    public float BreakScoreMin = 100;
    public float BreakScoreMax = 400;

    private List<Rigidbody2D> ChildRBodies = new List<Rigidbody2D>();
    private Rigidbody2D RBody;
    private Character LastTouchingCharacter = null;

    // Start is called before the first frame update
    void Start()
    {
        CurrentBreakingForce = BreakingForce;
        RBody = GetComponent<Rigidbody2D>();
        ChildRBodies.AddRange(GetComponentsInChildren<Rigidbody2D>());
        ChildRBodies.Remove(RBody);
    }

    public void Kill()
    {
        Debug.Log("Kill");
        CurrentBreakingForce = 0;
        LastTouchingCharacter.AddScore(transform.position, Random.Range(BreakScoreMin, BreakScoreMax));
        foreach (Rigidbody2D Child in ChildRBodies)
        {
            Child.transform.SetParent(null);
            Child.simulated = true;
            Child.velocity = RBody.velocity;
        }

        Destroy(gameObject);
    }

    public void DoDamage(float Normal)
    {
        LastTouchingCharacter.AddScore(transform.position, Random.Range(DamageScoreMin, DamageScoreMax));
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.rigidbody != null)
        {
            string LayerName = LayerMask.LayerToName(collision.rigidbody.gameObject.layer).ToLower();
            if (LayerName == "character")
                LastTouchingCharacter = collision.rigidbody.GetComponent<Character>();
            else if (collision.rigidbody.GetComponent<BreakableItem>() != null && collision.rigidbody.GetComponent<BreakableItem>().LastTouchingCharacter != null)
                LastTouchingCharacter = collision.rigidbody.GetComponent<BreakableItem>().LastTouchingCharacter;
        }

        if(LastTouchingCharacter != null)
        {
            float ImpactForce = collision.relativeVelocity.magnitude;
            CurrentBreakingForce -= ImpactForce;

            if (CurrentBreakingForce <= 0)
                Kill();
            else
                DoDamage(ImpactForce / BreakingForce);
        }
    }
}
