using CommonAI.data;
using CommonAI.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XmdsCommonSkill.Plugin.CardSkill;

namespace XmdsCommonServer.Plugin.Base
{
	public abstract class JSGCardDataBase : ICardData
	{
		public static readonly byte TRIGGER_NUM = 4;

		protected int mCards = 0;
		protected CardType[] mCardData = new CardType[(int)CardType.Max];

		public virtual void RefreshCardInfo(XmdsVirtual unit) { }
		public virtual void RefreshCardInfo(XmdsVirtual unit, byte[] cardData) { }
		public virtual void SendTriggerInfo(XmdsVirtual player, CardTriggerResult result, int skillId, byte[] cardData) { }

		public int GetCardNums()
		{
			return this.mCards;
		}

		public void ReSet(XmdsVirtual unit)
		{
			this.mCards = 0;
			for (int i = 0; i < (int)CardType.Max; i++)
			{
				mCardData[i] = CardType.Max;
			}

			if (unit != null)
			{
				this.RefreshCardInfo(unit);
			}
		}

		public CardTriggerResult AddCard(XmdsVirtual unit, GenCardData cardData)
		{
			if (mCards + cardData.nums >= TRIGGER_NUM)
			{
				CardTriggerResult result = new CardTriggerResult();
				byte[] cardNum = new byte[(int)CardType.Max];

				for (int i = 0; i < mCards; i++)
				{
					cardNum[(int)mCardData[i]]++;
					result.cardData[i] = (byte)mCardData[i];
				}

				cardNum[(int)cardData.type] = (byte)(cardNum[(int)cardData.type] + (TRIGGER_NUM - mCards));
				//1. 触发结果
				byte sameMax = 0, sameIndex = 0;
				for (byte i = 0; i < (byte)CardType.Max; i++)
				{
					if (cardNum[i] > sameMax)
					{
						sameMax = cardNum[i];
						sameIndex = i;
					}
				}

				//2. 保存触发记录
				for(int i = mCards; i < TRIGGER_NUM; i++)
				{
					result.cardData[i] = (byte)cardData.type;
				}

				//填充剩余卡牌
				mCards = Math.Min(TRIGGER_NUM - 1, mCards + cardData.nums - TRIGGER_NUM);
				for (int i = 0; i < mCards; i++)
				{
					mCardData[i] = cardData.type;
				}

				
				result.type = sameMax <= 1 ? CardType.Max : (CardType)(sameIndex);
				result.sameNums = cardNum[sameIndex];

				//刷一次之前的球信息
				this.RefreshCardInfo(unit, result.cardData);
				//刷当前的数据
				this.RefreshCardInfo(unit);
				return result;
			}
			else
			{
				for (int i = mCards; i < mCards + cardData.nums; i++)
				{
					mCardData[i] = cardData.type;
				}
				mCards = mCards + cardData.nums;
				this.RefreshCardInfo(unit);
				return null;
			}
		}

		public CardType GetCardData(int index)
		{
			if(index < 0 || index >= mCards)
			{
				return CardType.Max;
			}

			return this.mCardData[index];
		}
	}
}