/*
<copyright file="BGGCSetRelated.cs" company="BansheeGz">
    Copyright (c) 2018-2021 All Rights Reserved
</copyright>
*/

using GameCreator.Core;
using GameCreator.Variables;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;

#endif

namespace BansheeGz.BGDatabase
{
    /// <summary>
    ///  set database relationSingle value  
    /// </summary>
    public class BGGCSetRelated : BGGCSetA
    {
        [VariableFilter(Variable.DataType.Number)]
        public VariableProperty valueVar;

        [SerializeField] [HideInInspector] private int value;

        public override bool IsSupported(BGField field)
        {
            return field is BGFieldRelationSingle;
        }

        protected override void AssignUsingVar(GameObject target, BGGCCell cell)
        {
            if (!IsValid(valueVar)) return;

            var val = Mathf.RoundToInt((float) valueVar.Get(target));
            Assign(cell, val);
        }

        protected override void AssignUsingValue(GameObject target, BGGCCell cell)
        {
            Assign(cell, value);
        }

        private static void Assign(BGGCCell cell, int value)
        {
            var relatedMeta = ((BGFieldRelationSingle) cell.field).RelatedMeta;
            if (value >= relatedMeta.CountEntities)
            {
                Debug.Log($"WARNING! BGDatabase: can not set related entity cause the value is in invalid range! meta {relatedMeta.Name}, invalid index {value}");
                return;
            }

            var val = value < 0 ? null : relatedMeta.GetEntity(value);
            cell.Value = val;
        }
        // +--------------------------------------------------------------------------------------+
        // | EDITOR                                                                               |
        // +--------------------------------------------------------------------------------------+

#if UNITY_EDITOR
        public static new string NAME = "BansheeGz/Set related";
        protected override string Title => "BGDatabase: Set related";

        public override void EditorGui()
        {
            base.EditorGui();
            EditorGUILayout.PropertyField(Prop(UseVarForValue ? nameof(valueVar) : nameof(value)));
        }
#endif
    }
}