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

using System;
using GameCreator.Runtime.Common;
using UnityEngine;

namespace BansheeGz.BGDatabase
{
    /// <summary>
    /// reference to a table row 
    /// </summary>
    [Serializable]
    public abstract class BGGCRowA : BGGCTableA
    {
        public enum BGGCRowSource : byte
        {
            Index,
            Id,
            Name,
        }

        [SerializeField] private BGGCRowSource rowSource;

        [SerializeField] private PropertyGetInteger rowIndexVar = GetDecimalInteger.Create(0);
        [SerializeField] private PropertyGetString rowIdVar = GetStringString.Create;
        [SerializeField] private PropertyGetString rowNameVar = GetStringString.Create;

        private BGEntity entity;

        public BGGCRowSource RowSource => rowSource;

        public BGEntity GetEntity(Args args)
        {
            //you can not cache the row!
            // if (entity?.Meta != null && !entity.Meta.IsDeleted) return entity;

            entity = null;
            var meta = Meta;
            if (meta == null) return null;

            switch (rowSource)
            {
                case BGGCRowSource.Index:
                    var trueRowIndex =  (int) rowIndexVar.Get(args);
                    if (trueRowIndex < 0 || trueRowIndex >= meta.CountEntities)
                    {
                        Debug.Log($"WARNING! BGDatabase: row index in invalid range! {meta.Name} table, invalid index {trueRowIndex}");
                        return null;
                    }
                    entity = meta.GetEntity(trueRowIndex);
                    break;
                case BGGCRowSource.Id:
                    var trueRowId = rowIdVar.Get(args);
                    if (!BGId.TryParse(trueRowId, out var entityId))
                    {
                        Debug.Log($"WARNING! BGDatabase: row ID invalid! {meta.Name} table, invalid ID [{trueRowId}]");
                        return null;
                    }
                    entity = meta.GetEntity(entityId);
                    break;
                case BGGCRowSource.Name:
                    var trueRowName = rowNameVar.Get(args);
                    entity = meta.GetEntity(trueRowName);
                    break;
                default:
                    throw new ArgumentOutOfRangeException(nameof(rowSource));
            }

            return entity;
        }
    }
}