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

public class Butterfly : MonoBehaviour {

    public float maxDistance = 2.0f;
    public float speed = 0.2f;
    public float nextDistanceTime = 5.0f;
    float curDistTime = 0.0f;

    public float animSpeed = 1.0f;
    public Sprite [] frames;
    int curFrame = 0;
    float time = 0.0f;

    Vector3 target;
    Vector3 lastPos;

    [SerializeField] SpriteRenderer sr;
    [SerializeField] Transform transf;

    [SerializeField] Vector3 leftRotation = new Vector3(0.0f, 180.0f, 0.0f);
    [SerializeField] Vector3 rightRotation = new Vector3(0.0f, 0.0f, 0.0f);

    Transform thisTransf;

    private void Awake() {
        thisTransf = transform;
        target = lastPos = transf.position;
    }

    void Update () {
		time += Time.deltaTime * animSpeed;

        if(time > 1.0f) {
            time -= 1.0f;
            curFrame = (curFrame+1)% frames.Length;
            sr.sprite = frames[curFrame];
        }

        Move();
    }

    float ratio = 0.0f;

    void Move() {
        curDistTime += Time.deltaTime;
        if(curDistTime > nextDistanceTime) {
            curDistTime -= nextDistanceTime;

            lastPos = transf.position;
            target = thisTransf.position + Random.insideUnitSphere * maxDistance;
            target.y = 0;

            ratio = 0.0f;

            if(target.x < lastPos.x) {
                transf.eulerAngles = leftRotation;
            }
            else {
                transf.eulerAngles = rightRotation;
            }
        }

        transf.position = Vector3.Lerp(lastPos, target, ratio );

        ratio = ratio + (1.0f - ratio) * speed * Time.deltaTime;
    }
}
