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

namespace Arugula.Games
{
    public class DestructibleFlash : MonoBehaviour
    {
        [ColorUsage(true, true)]
        public Color flashColor;
        public new Renderer renderer;
        public int materialIndex;
        public DestructibleObject destructibleObject;

        [Range(0, 1)]
        public float flashAmount = 1;
        public float duration = 0.1f;

        float endFlashTime;
        bool flashing = false;

        private void Start()
        {
            if (destructibleObject == null)
                destructibleObject = DestructibleObject.Get(gameObject);

            destructibleObject.OnDamaged += OnDamaged;
        }

        private void OnDamaged(DestructibleObject obj, DamageInfo info)
        {
            renderer.materials[materialIndex].SetColor("_EmissionColor", flashColor * flashAmount);
            endFlashTime = Time.time + duration;
            flashing = true;
        }

        private void Update()
        {
            if (flashing)
            {
                if (Time.time > endFlashTime)
                {
                    renderer.materials[materialIndex].SetColor("_EmissionColor", Color.black);
                    flashing = false;
                }
            }
        }
    }
}