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

public class Package : Grabable
{
    [SerializeField] private MeshRenderer _renderer;

   private int _life = 10;

    [HideInInspector] public float LifeTime = 0;
    [SerializeField] private ParticleSystem _particles;
    [SerializeField] private Texture2D[] _colorDefines;

    public int TargetType = -1;


    public void Setup(int targetType, Vector3 force)
    {
        base.Setup(force);
    
        TargetType = targetType;

        var color = GameController.Instance.PortalColorPresets[targetType].BoxColor;
        _renderer.material.SetColor("_Color", color);

        int index =Random.Range(0, _colorDefines.Length);
        _renderer.material.SetTexture("_ColorDefineTex", _colorDefines[index]);
    }


    public void Awake()
    {
        //GameController.Instance.SetupMaterialForPortals(_renderer);
    }


    public override void Update()
    {      
        base.Update();

        LifeTime += Time.deltaTime;

        if (transform.position.y < -3)
            DestroyMe();

        if (_life <= 0)
        {
            GameController.Instance.PackageFailed();
            DestroyMe();
        }
    }

    public override void PickedUp()
    {
        base.PickedUp();
    }

    public override void Released()
    {
        base.Released();  
    }
 
    void FixedUpdate()
    {
        if (LifeTime < 2)
            return;

        for(int i = 0; i < GameController.Instance.Portals.Length; i++)
        {
            //4.4: ok i guess  ----   5.5: is easy peasy
            float _minRange = 5.1f;


            Vector3 portalPos = GameController.Instance.Portals[i].transform.position - GameController.Instance.Portals[i].transform.forward * 0.5f;
            Vector3 delta = portalPos - transform.position;
            float distance = delta.magnitude;

            if(distance < _minRange)
            {
                float force = 1f -( distance / _minRange);
                force = Mathf.Pow(force, 1.5f);

                RigidBody.AddForce(delta.normalized * force * 50f, ForceMode.Force);
            }
        }
    }


    public void DestroyMe(bool negative)
    {
        if (negative)
            GameController.Instance.PackageFailed();

        DestroyMe();
    }

    public override void DestroyMe()
    {
        GameController.Instance.Packages.Remove(this);
        base.DestroyMe();
    }

    

    public void GetHit()
    {
        _particles.Play();
        _life--;
    }

    


}
