using UnityEngine;
using System.Collections;

public class PuddleBit : MonoBehaviour 
{
    public PhysicsMaterial2D[] PhysicsMaterials2D;
    public float DurationPerMaterial = 1;
    public float LifeDuration = 10;
    public LayerMask _groundLayerMask;

    private CircleCollider2D _collider;
    private float _lifeStart = 0;
    private int _indexMaterial = 0;

	// Use this for initialization
	void Start ()
    {
        _collider = GetComponent<CircleCollider2D>();
        SetPhysicsMaterial2D();
	}
	
	// Update is called once per frame
	void Update ()
    {
        if (_lifeStart > 0)
        {
            float lifeTime = Time.time - _lifeStart;

            if (lifeTime >= LifeDuration)
            {
                //Debug.LogFormat("PuddleBit : destroy\n");
                DestroyObject(gameObject);
            }
            else
            {
                int index = (int)(lifeTime / DurationPerMaterial);
                index = Mathf.Min(index, PhysicsMaterials2D.Length - 1);

                if (_indexMaterial != index)
                {
                    _indexMaterial = index;
                    SetPhysicsMaterial2D();
                }
            }
        }
	}

    private void SetPhysicsMaterial2D()
    {
        _collider.sharedMaterial = PhysicsMaterials2D[_indexMaterial];
        _collider.enabled = false;  // Workaround for Unity3D bug (http://fogbugz.unity3d.com/default.asp?577228_no7i4p502369okao)
        _collider.enabled = true;
        //Debug.LogFormat("PuddleBit : set material to {0}\n", _indexMaterial);
    }

    public void OnCollisionEnter2D(Collision2D collision)
    {
        int layerMask = 1 << collision.gameObject.layer;
        if ((layerMask & _groundLayerMask) != 0)
        {
            if (_lifeStart == 0)
            {
                //Debug.Log("PuddleBit : start life\n");
                _lifeStart = Time.time;
            }
        }
    }
}
