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

namespace mgaia.Utils.Animations
{
    public class GameobjectPositionIncrementAnimation : AbstractCodeAnimation
    {
        private GameObject[] mGameobjects;
        private Vector3[] mOriginalPositions;

        public GameobjectPositionIncrementAnimation(float[] keyTimes, ValueType[] keyValues, ValueType initialValue, bool loop) : base(keyTimes, keyValues, initialValue, loop) { }

        protected override void Lerp(ValueType fromValue, ValueType toValue, float normalizedTime)
        {
            Vector3 convertedFromValue = (Vector3)fromValue;
            Vector3 convertedToValue = (Vector3)toValue;
            Vector3 targetValue = Vector3.Lerp(convertedFromValue, convertedToValue, normalizedTime);

            if (!float.IsNaN(targetValue.x) && !float.IsNaN(targetValue.y) && !float.IsNaN(targetValue.z))
            {
                for (int i = 0; i < mGameobjects.Length; i++)
                {
                    float xValue = mGameobjects[i].transform.position.x;
                    float yValue = mGameobjects[i].transform.position.y;
                    float zValue = mGameobjects[i].transform.position.z;

                    if (targetValue.x != 0.0f)
                    {
                        xValue = mOriginalPositions[i].x + targetValue.x;
                    };

                    if (targetValue.y != 0.0f)
                    {
                        yValue = mOriginalPositions[i].y + targetValue.y;
                    };

                    if (targetValue.z != 0.0f)
                    {
                        yValue = mOriginalPositions[i].z + targetValue.z;
                    };

                    mGameobjects[i].transform.position = new Vector3(xValue, yValue, zValue);
                }
            }
        }

        protected override void OnActivateAnimation(object[] objs)
        {
            mGameobjects = objs.Select(obj => obj as GameObject).ToArray();
            mOriginalPositions = mGameobjects.Select(gameObj => gameObj.transform.position).ToArray();
        }
    }
}