/*================================================================
Product:    GGJ-2017
Developer:  Onur Tanrıkulu
Company:    Onur Tanrikulu
Date:       21/01/2017 15:31

Copyright (c) 2017 Onur Tanrikulu. All rights reserved.
================================================================*/

using UnityEngine;

public class WaveController : MonoBehaviour
{
   #region Fields
    private const float speed = 5f;
    private const float growSpeed = 0.5f;
    private const float forcePower = 1000f;
    private float animateDelay;
    private SpriteRenderer spriteRenderer;
    private Sprite[] sprites;
    private int spriteId;
   #endregion
 
   #region Constructors
   // code here
   #endregion
 
   #region Properties
   // code here
   #endregion
 
   #region Methods
    private void Start()
    {
        spriteRenderer = GetComponent<SpriteRenderer>();
        sprites = Resources.LoadAll<Sprite>("Sprites/wave");
    }

    private void Update()
    {          
        float dt = Time.deltaTime;
        animateDelay += dt;

        if (animateDelay > 1/60)
        {
            animateDelay = 0;
            spriteRenderer.sprite = sprites[spriteId];

            if (spriteId == sprites.Length - 1)
            {
                spriteId = 0;
            }
            else
            {
                spriteId++;
            }
        }

        transform.Translate(Vector2.right * speed * dt);
        transform.localScale = Vector2.Lerp(transform.localScale, Vector2.one, dt * growSpeed);

        if (Vector2.Distance(transform.localScale, Vector2.one) < 0.2f)
        {
            gameObject.SetActive(false);
        }
    }

    private void OnTriggerEnter2D(Collider2D collider)
    {
        GameObject go = collider.gameObject;

        if (go.tag.Equals("Box"))
        {

            Vector2 current = transform.position;
            Vector2 target = collider.transform.position;
            Vector2 heading = target - current;
            Vector2 direction = heading / heading.magnitude;

            go.GetComponent<Rigidbody2D>().AddForce(direction * 100f);
            gameObject.SetActive(false);
        }
    }
   #endregion
}
