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

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

        public GameobjectRelativeScaleAnimation(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;
            for (int i = 0; i < mGameobjects.Length; i++)
            {
                float xTargetValue = Mathf.Lerp(convertedFromValue.x * mBaseScales[i].x, convertedToValue.x * mBaseScales[i].x, normalizedTime);
                float yTargetValue = Mathf.Lerp(convertedFromValue.y * mBaseScales[i].y, convertedToValue.y * mBaseScales[i].y, normalizedTime);
                float zTargetValue = Mathf.Lerp(convertedFromValue.z * mBaseScales[i].z, convertedToValue.z * mBaseScales[i].z, normalizedTime);
                if (!float.IsNaN(xTargetValue) && !float.IsNaN(yTargetValue) && !float.IsNaN(zTargetValue))
                {
                    mGameobjects[i].transform.localScale = new Vector3
                    (
                        xTargetValue,
                        yTargetValue,
                        zTargetValue
                    );
                }
            }
        }

        protected override void OnActivateAnimation(object[] objs)
        {
            mGameobjects = objs.Select(obj => obj as GameObject).ToArray();
            mBaseScales = mGameobjects.Select(text => text.transform.localScale).ToArray();
        }
    }
}