/**
 * Copyright(c) Live2D Inc. All rights reserved.
 *
 * Use of this source code is governed by the Live2D Open Software license
 * that can be found at https://www.live2d.com/eula/live2d-open-software-license-agreement_en.html.
 */
using Live2D.Cubism.Core.Unmanaged;
using Live2D.Cubism.Framework;
using UnityEngine;
namespace Live2D.Cubism.Core
{
    /// 
    /// Single  part.
    /// 
    [CubismDontMoveOnReimport]
    public sealed class CubismPart : MonoBehaviour
    {
        #region Factory Methods
        /// 
        /// Creates parts for a .
        /// 
        /// Handle to unmanaged model.
        /// Parts root.
        internal static GameObject CreateParts(CubismUnmanagedModel unmanagedModel)
        {
            var root = new GameObject("Parts");
            // Create parts.
            var unmanagedParts = unmanagedModel.Parts;
            var buffer = new CubismPart[unmanagedParts.Count];
            for (var i = 0; i < buffer.Length; ++i)
            {
                var proxy = new GameObject();
                buffer[i] = proxy.AddComponent();
                buffer[i].transform.SetParent(root.transform);
                buffer[i].Reset(unmanagedModel, i);
            }
            return root;
        }
        #endregion
        /// 
        /// Unmanaged parts from unmanaged model.
        /// 
        private CubismUnmanagedParts UnmanagedParts { get; set; }
        /// 
        ///  backing field.
        /// 
        [SerializeField, HideInInspector]
        private int _unmanagedIndex = -1;
        /// 
        /// Position in unmanaged arrays.
        /// 
        internal int UnmanagedIndex
        {
            get { return _unmanagedIndex; }
            private set { _unmanagedIndex = value; }
        }
        /// 
        /// Copy of Id.
        /// 
        public string Id
        {
            get
            {
                // Pull data.
                return UnmanagedParts.Ids[UnmanagedIndex];
            }
        }
        /// 
        /// Current opacity.
        /// 
        [SerializeField, HideInInspector]
        public float Opacity;
        /// 
        /// Revives instance.
        /// 
        /// TaskableModel to unmanaged unmanagedModel.
        internal void Revive(CubismUnmanagedModel unmanagedModel)
        {
            UnmanagedParts = unmanagedModel.Parts;
        }
        /// 
        /// Restores instance to initial state.
        /// 
        /// TaskableModel to unmanaged unmanagedModel.
        /// Position in unmanaged arrays.
        private void Reset(CubismUnmanagedModel unmanagedModel, int unmanagedIndex)
        {
            Revive(unmanagedModel);
            UnmanagedIndex = unmanagedIndex;
            name = Id;
            Opacity = UnmanagedParts.Opacities[unmanagedIndex];
        }
    }
}