using UnityEngine;
using System.Collections;
using com.deeperbeige.lib;

namespace com.deeperbeige.whiteout
{
	internal class BallPath : MonoBehaviour
	{
		public Material ribbonMaterial = null;

		//LineRenderer line;
		//int          segments = 0;
		private SmoothLine   ribbon;
		private GameObject   ball;
		private int          frame = 0;
		private float        explodeTime = Mathf.Infinity;

		public  Player       player { get; set; }

		public  Color32      colour { get; set; }

        private const float minSpeed = 0.2f * 0.2f;

        private int belowMinSpeedFrameCount = 0;

		private void Start()
		{
			//line = GameObjects.FindNested(gameObject, "Trail").GetComponent<LineRenderer>();
		}

		public void Init()
		{
			colour = Colours.fromRGBA(colour.r + Maths.RandomInt(-30, 30),
			                          colour.g + Maths.RandomInt(-30, 30),
			                          colour.b + Maths.RandomInt(-30, 30),
			                          Maths.RandomInt(100, 255));

			ball = GameObjects.FindNested(gameObject, "Ball");
			ribbon = new SmoothLine(colour, gameObject, ribbonMaterial);

			explodeTime = Time.time + 10f;
			Sample();
		}

		private void Update()
		{
			frame++;
			if (ball == null) return;
			if (frame < 3)    return;

			// Check for explosions
			if (Time.time > explodeTime)
			{
                Debug.Log("Time greater than explodeTime");
				Explode();
				return;
			}

            if (belowMinSpeedFrameCount > 60) {
                Debug.Log("belowMinSpeedFrameCount greater than 60");
                Explode ();
                belowMinSpeedFrameCount = 0;
                return;
            }

            if (ball.transform.position.magnitude > 15.0f) {
                Debug.Log("Asplode! Position was: " + ball.transform.position.magnitude);
                Explode ();
                return;
            }


			// Grow paint
			if ((frame % 10) == 0) Sample();
		}

        private void FixedUpdate()
        {        
            if (null != ball) {
                if (ball.rigidbody.velocity.sqrMagnitude < minSpeed) {
                    if (belowMinSpeedFrameCount % 5 ==1) {
                        Debug.Log("belowMinSpeedFrameCount: " + belowMinSpeedFrameCount);
                    }
                    belowMinSpeedFrameCount++;
                } else {
                    belowMinSpeedFrameCount = 0;
                }
            }
        }

		public void Explode()
		{
			Destroy(ball);

			ball = null;
		}

		private void Sample()
		{
			if (frame < 5)    return;
			if (ball == null) return;
			ribbon.addPoint(ball.transform.localPosition + Vector3.down * 0.45f);

			//line.SetVertexCount(++segments);
			//line.SetPosition(segments - 1, ball.transform.localPosition);
		}
	}
}
