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

public class Dot : MonoBehaviour {
    public static List<Dot> Dots;

    private Transform cut;
    private SpriteRenderer cutRenderer;
    private bool fresh = true;

    void Awake()
    {
        if (Dots == null)
        {
            Dots = new List<Dot>();
        }

        Dots.Add(this);
        cut = transform.GetChild(0);
    }

	void Start () {
        cutRenderer = cut.GetComponent<SpriteRenderer>();
        cut.gameObject.SetActive(false);
    }

    public void CutBegin()
    {
        cut.gameObject.SetActive(true);
    }

    public void CutLine(Vector2 diff)
    {
        cut.rotation = Quaternion.Euler(0, 0, Mathf.Atan2(diff.y, diff.x) / Mathf.PI * 180);
        cut.localScale = new Vector3(diff.magnitude * 1.5f, 0.1f, 1);
        cut.localPosition = diff * 0.5f;
        cutRenderer.color = new Color(1, 1, 1, Mathf.Clamp(diff.magnitude, 0.1f, 1f));
    }

    public void CutPull(Vector2 point)
    {
        Vector2 tmp = ((Vector3)point - transform.position);
        Vector2 diff = tmp.normalized * 2;
        CutLine(diff);
    }

    public void CutPush(Vector2 point)
    {
        Vector2 tmp = (transform.position - (Vector3)point);
        Vector2 diff =  tmp.normalized * 2;
        CutLine(diff);
    }

    public void CutEnd()
    {
        cut.gameObject.SetActive(false);
    }

    public void Impulse(Vector2 direction)
    {
        GetComponent<Rigidbody2D>().velocity *= 0.5f;
        GetComponent<Rigidbody2D>().velocity += direction * 8;
        GetComponent<SpriteRenderer>().color = new Color(0.5f, 0.5f, 0.5f);
        fresh = false;
    }

    void OnCollisionEnter2D(Collision2D coll)
    {
        if (coll.gameObject.tag == "WALL")
        {
            Vector2 vel = GetComponent<Rigidbody2D>().velocity;
            GetComponent<Rigidbody2D>().velocity = (vel + Random.Range(-1, 1) * new Vector2(-vel.y, vel.x) * 0.5f).normalized * vel.magnitude;
            fresh = true;
            GetComponent<SpriteRenderer>().color = Color.white;
        }
    }

    void OnDestroy()
    {
        Dots.Remove(this);
    }

    public bool IsFresh()
    {
        return fresh;
    }
}
