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

public class ShadowPart : MonoBehaviour {

    private List<LightSource> lightSources;
    private List<float> lightSourceDistances;
    private float lightSensibility = 1.5f;
    private ParticleSystem system;

    private bool isDying = false;

	void Start () 
    {
        lightSources = new List<LightSource>();
        lightSourceDistances = new List<float>();
        lightSources.Add(GameObject.Find("/Player").transform.GetComponent<LightSource>());
        lightSourceDistances.Add(-1);
        Shadow shadow = transform.parent.GetComponent<Shadow>();
        foreach (LightSource source in shadow.lightSources)
        {
            lightSources.Add(source);
            lightSourceDistances.Add(Vector2.Distance(new Vector2(transform.position.x, transform.position.z), new Vector2(source.transform.position.x, source.transform.position.z)));
        }
        system = transform.GetComponent<ParticleSystem>();
	}
	
	void Update () 
    {
        if (isDying)
        {
            if (system.particleCount == 0)
                GameObject.Destroy(gameObject);
            return;
        }
        bool shouldBeOn = true;
        bool shouldDestroy = true;
        int i = 0;
        foreach (LightSource source in lightSources)
        {
            float dist = lightSourceDistances[i]; 
            if(dist == -1) 
                dist = Vector2.Distance(new Vector2(transform.position.x, transform.position.z), new Vector2(source.transform.position.x, source.transform.position.z));

            if (dist < lightSensibility && source.isLighted)
                shouldBeOn = false;
            if (!source.isLighted)
                shouldDestroy = false;

            ++i;
        }
        system.enableEmission = shouldBeOn;
        if (shouldDestroy && lightSources.Count > 1)
        {
            system.enableEmission = false;
            isDying = true;
        }
	}
}
