using CommonAI.Zone;
using CommonLang.Geometry;
using ET.Client;
using ET.EventType;
using ET.Server;
using System;

namespace ET
{
    [Event(SceneType.None)]
    public class BattleFuncHandler : BEvent<BattleFunc>
    {
        public override void OnEvent(BattleFunc a)
        {
            Log.Debug($"Battle Func:{a.FuncIndex}");
            asyncHandler(a.FuncIndex);
        }

        //获得当前战场focus中心(当前塔位置)
        private Vector2 vecTemp = new Vector2();
        private Vector2 GetCurBattleCenter()
        {
            foreach(var tid in ConstGame.TowerTemplateIDs)
            {
                var tower = BattleMgr.Instance.GetUnitByTemplateID(tid);
                if(tower != null && !tower.IsDead)
                {
                    vecTemp.X = tower.ZUnit.X;
                    vecTemp.Y = tower.ZUnit.Y;
                    return vecTemp;
                }
            }
            return new Vector2(0, 0);
        }

        private void asyncHandler(BattleFunc.Index index)
        {
            var session = PlayerComponent.Instance.ClientScene().GetComponent<SessionComponent>().Session;
            switch (index)
            {
                case BattleFunc.Index.Func2:
                    var units = new int[] {105, 108, 111, 117};
                    var centerpos = GetCurBattleCenter();
                    var rand = new Random();
                    foreach (var id in units)
                    {
                        float r = (rand.Next(1000)) / 100.0f + 5;
                        double ang = rand.Next(180) / 180.0f * Math.PI + Math.PI;
                        Log.Debug($"rand unit r({r}), ang({ang})");
                        float x = centerpos.X + (float)(r * Math.Cos(ang));
                        float y = centerpos.Y - (float)(r * Math.Sin(ang));

                        session.Call(new C2G_AddUnitsToMap()
                        {
                            UnitId = id,
                            Force = 1,
                            X = (int)x,
                            Y = (int)y
                        }).Coroutine();
                    }
                    break;
                default:
                    break;
            }
        }
    }

    //发送战斗服指令相关
    public partial class BattleMgr
    {
        private bool autoFight;
        public bool AutoFight
        {
            get
            {
                return autoFight;
            }
            set
            {
                if(value == autoFight) return;
                else
                {
                    autoFight = value;
                }
            }
        }

        public CommonAI.Zone.Action SetAutoFight(bool flag)
        {
            return new UnitGuardAction(UnitMgr.Instance.ActorId, flag, CommonAI.XmdsConstConfig.AUTO_GUARD_MODE_POINT);
        }
    }

}