﻿using System;
using System.Collections.Generic;
using HutongGames.PlayMaker;
using UnityEngine;

namespace BansheeGz.BGDatabase
{
    public abstract class BGPlaymakerResetValuesTableBasedA : BGPlaymakerResetValuesA
    {
        [HutongGames.PlayMaker.Tooltip("Target meta(table) name")]
        public FsmString meta;

        [HutongGames.PlayMaker.Tooltip("Comma separated list of fields for resetting values to default ones. If not set, all fields will be included, except fieldsToExclude")]
        public FsmString fieldsToInclude;

        [HutongGames.PlayMaker.Tooltip("Comma separated list of fields to skip while resetting values to default ones. The highest priority")]
        public FsmString fieldsToExclude;

        public BGMetaEntity Meta
        {
            get
            {
                if (meta.IsNone || string.IsNullOrWhiteSpace(meta.Value)) throw new Exception("Required 'meta' field is not set!");
                var metaName = meta.Value.Trim();
                var table = BGRepo.I.GetMeta(metaName);
                if (table == null) throw new Exception($"Meta with name={metaName} can not be found!");
                return table;
            }
        }

        public List<BGField> GetFields(BGMetaEntity table)
        {
            var fieldList = new List<BGField>();

            //include
            if (ForEachToken(fieldsToInclude, token => fieldList.Add(table.GetField(token))) == 0) table.FindFields(fieldList);

            //exclude
            ForEachToken(fieldsToExclude, token =>
            {
                var index = fieldList.FindIndex(field => field.Name == token);
                if (index != -1) fieldList.RemoveAt(index);
                else Debug.Log($"Can not exclude field {token}, cause it's not included or does not exist");
            });

            return fieldList;
        }

        public override void Reset()
        {
            base.Reset();
            meta = null;
            fieldsToInclude = null;
            fieldsToExclude = null;
        }
       
    }
}