/*
<copyright file="BGGCCellA.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's cell 
    /// </summary>
    [Serializable]
    public abstract class BGGCCellA : BGGCRowA
    {
        //these are the references to database cell
        [SerializeField] private string fieldId;
        private BGField field;


        public BGField Field
        {
            get
            {
                if (field != null && !field.IsDeleted && field.Meta != null) return field;
                var meta = Meta;
                if (meta == null) return null;
                field = null;
                if (string.IsNullOrEmpty(fieldId)) return null;
                if (!BGId.TryParse(fieldId, out var databaseFieldId)) return null;
                field = meta.GetField(databaseFieldId, false);

                return field;
            }
        }

        public string FieldId
        {
            set
            {
                fieldId = value;
                field = null;
            }
        }

        public BGGCCell? GetCell(Args args)
        {
            var f = Field;
            if (f == null) return null;
            var e = GetEntity(args);
            if (e == null) return null;
            return new BGGCCell(f, e);
        }

        public abstract bool IsSupported(BGField field);

        public struct BGGCCell
        {
            public readonly BGField field;
            public readonly BGEntity row;

            public BGGCCell(BGField field, BGEntity row)
            {
                this.field = field;
                this.row = row;
            }

            public object Value
            {
                get => field.GetValue(row.Index);
                set => field.SetValue(row.Index, value);
            }
        }
    }
}