// Copyright (c) 2011-2017 Thinksquirrel Inc.

using UnityEngine;

namespace Thinksquirrel.Thinkscroller
{
    /// <summary>
    /// Scroll layer animation component.
    /// </summary>
    /// <remarks>
    /// This class exposes the properties of a scroll layer for Unity animation curves.
    /// </remarks>
    [RequireComponent(typeof(ScrollLayer))]
    [AddComponentMenu("Thinkscroller/Scroll Layer Animation")]
    [ExecuteInEditMode]
    public sealed class ScrollLayerAnimation : ThinkscrollerMonoBehaviourBase
    {
        [HideInInspector] public float weight;
        [HideInInspector] public float scrollSpeed;
        [HideInInspector] public Vector2 scrollMod;
        [HideInInspector] public Vector2 offset;
        [HideInInspector] public Vector2 pixelOffset;
        [HideInInspector] public Vector2 padding;

        private ScrollLayer scrollLayer;

        /// <summary>
        /// Syncs the component to the scroll layer.
        /// </summary>
        /// <remarks>
        /// If you edit a scroll layer's properties through code and this component is present, you will need to call this method.
        /// </remarks>
        public void SyncToScrollLayer()
        {
            weight = scrollLayer.GetWeight();
            scrollSpeed = scrollLayer.GetScrollSpeed();
            scrollMod = scrollLayer.GetScrollMod();
            offset = scrollLayer.offset;
            pixelOffset = scrollLayer.pixelOffset;
            padding = scrollLayer.padding;
        }

        private void Awake()
        {
            scrollLayer = GetComponent<ScrollLayer>();

            SyncToScrollLayer();
        }

        private void LateUpdate()
        {
            var refresh = false;

            scrollLayer.SetWeight(weight);
            scrollLayer.SetScrollSpeed(scrollSpeed);
            scrollLayer.SetScrollMod(scrollMod);

            if (scrollLayer.offset != offset)
            {
                refresh = true;
                scrollLayer.offset = offset;
            }

            if (scrollLayer.pixelOffset != pixelOffset)
            {
                refresh = true;
                scrollLayer.pixelOffset = pixelOffset;
            }

            if (scrollLayer.padding != padding)
            {
                refresh = true;
                scrollLayer.padding = padding;
            }

            if (refresh && scrollLayer.isAutoBillboard)
            {
                scrollLayer.RefreshBillboard(true, false, false);
            }
        }
    }
}
