using Darkmatter.Core;
using Darkmatter.Domain;
using Darkmatter.Presentation;
using System.Collections.Generic;
using UnityEngine;
using VContainer;

public class Platform : MonoBehaviour, IPlatform 
{
    [SerializeField] private List<GameObject> _platformPiece = new List<GameObject>();
    [SerializeField] private Material _safeMaterial;
    [SerializeField] private Material _deathMaterial;
    [SerializeField] private ParticleSystem _particleSystem;

    //for selecting random color
    [SerializeField]private Color[] safeMaterialColors;
    [SerializeField] private Color[] deathMaterialColors;

    public List<GameObject> platformPiece => _platformPiece;
    public Material safeMaterial => _safeMaterial;
    public Material deathMaterial => _deathMaterial;

    private IPlatformRule _platformRule;
    private bool hasAchievedScore = false;

    [Inject] Player player;
    [Inject] IPool<Platform> pool;
    [Inject] IPlatformManager platformManager;
    [Inject] IScoreService IscoreService;
    [Inject] IAudioController IaudioController;

    private void Start()
    {
        if(_particleSystem == null) _particleSystem = GetComponent<ParticleSystem>();
        _safeMaterial.color = ReturnMaterialColor(safeMaterialColors);
        _deathMaterial.color = ReturnMaterialColor(deathMaterialColors);
    }

    Color ReturnMaterialColor(Color[] color)
    {
        return color[Random.Range(0,color.Length)];
    }
    public void SetPlatformRule(IPlatformRule platformRule)
    {
        _platformRule = platformRule;
        _platformRule.Execute(this);
    }

    private void OnTriggerEnter(Collider other)
    {
        if(other.CompareTag("Player") && !hasAchievedScore)
        {
            hasAchievedScore = true;
            IscoreService.AddScore();
            IaudioController.PlayScoredSound();
            _particleSystem.Play();
            HideThisPlatfromPiece();

        }
    }
    void HideThisPlatfromPiece()
    {
        foreach(var piece in _platformPiece)
        {
            piece.gameObject.SetActive(false);
        }
    }

    private void Update()
    {
        if (player.transform.position.y < transform.position.y-5f)
        {
            hasAchievedScore = false;
            pool.ReturnToPool(this);
            platformManager.BuildNewPlatform();
        }
    }
}









