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

using System;
using NodeCanvas.Framework;
using UnityEngine;

namespace BansheeGz.BGDatabase
{
    public abstract class BGNCRowA : BGNCTableA
    {
        public enum BGNCRowSource : byte
        {
            Index,
            Id,
            Name,
        }

        public BBParameter<BGNCRowSource> rowSource;
        public BBParameter<int> rowIndex;
        public BBParameter<string> rowId;
        public BBParameter<string> rowName;

        public BGEntity Entity
        {
            get
            {
                var meta = Meta;
                if (meta == null) return null;

                BGEntity entity = null;
                var rowSourceVal = rowSource.value;
                switch (rowSourceVal)
                {
                    case BGNCRowSource.Index:
                        var trueRowIndex = rowIndex.value;
                        CheckEntityIndex(meta, trueRowIndex);
                        entity = meta.GetEntity(trueRowIndex);
                        break;
                    case BGNCRowSource.Id:
                        var trueRowId = rowId.value;
                        if (!BGId.TryParse(trueRowId, out var entityId)) throw new Exception($"Can not retrieve an entity, cause ID value is not valid!");
                        entity = meta.GetEntity(entityId);
                        if (entity == null) throw new Exception($"Can not retrieve an entity, cause there is no entity with specified ID={entityId}!");
                        break;
                    case BGNCRowSource.Name:
                        var trueRowName = rowName.value;
                        entity = meta.GetEntity(trueRowName);
                        if (entity == null) throw new Exception($"Can not retrieve an entity, cause there is no entity with specified name={trueRowName}!");
                        break;
                    default:
                        throw new ArgumentOutOfRangeException(nameof(rowSource));
                }

                return entity;
            }
        }

        protected static void CheckEntityIndex(BGMetaEntity meta, int entityIndex)
        {
            if (entityIndex < 0 || entityIndex >= meta.CountEntities)
                throw new Exception($"Can not retrieve an entity, cause rowIndex is out of bounds! Valid range is 0-{(meta.CountEntities - 1)}" +
                                    $", row index={entityIndex}");

        }
    }
}