#if !FANTASY_WEBGL
using System;
using KCP;

#pragma warning disable CS1591
namespace NBC.Network.KCP
{
    public class KCPSettings
    {
        public int Mtu { get; private set; }
        public int SendWindowSize { get; private set; }
        public int ReceiveWindowSize { get; private set; }
        public int MaxSendWindowSize { get; private set; }

        public static KCPSettings Create(NetworkTarget networkTarget)
        {
            var settings = new KCPSettings();
            
            switch (networkTarget)
            {
                case NetworkTarget.Outer:
                {
                    // 外网设置470的原因:
                    // 1、mtu设置过大有可能路由器过滤掉
                    // 2、降低 mtu 到 470，同样数据虽然会发更多的包，但是小包在路由层优先级更高
                    settings.Mtu = 470;
                    settings.SendWindowSize = 512;
                    settings.ReceiveWindowSize = 512;
                    settings.MaxSendWindowSize = 512 * 512 * 7;
                    
                    break;
                }
                default:
                {
                    throw new NotSupportedException($"KCPServerNetwork NotSupported NetworkType:{networkTarget}");
                }
            }

            return settings;
        }
    }

    public static class KCPFactory
    {
        public const int FANTASY_KCP_RESERVED_HEAD = 5;

        public static Kcp Create(NetworkTarget networkTarget, uint conv, KcpCallback output, out KCPSettings kcpSettings)
        {
            var kcp = new Kcp(conv, output, FANTASY_KCP_RESERVED_HEAD);
            kcpSettings = KCPSettings.Create(networkTarget);
            kcp.SetNoDelay(1, 5, 2, 1);
            kcp.SetWindowSize(kcpSettings.SendWindowSize, kcpSettings.ReceiveWindowSize);
            kcp.SetMtu(kcpSettings.Mtu);
            kcp.SetMinrto(30);
            return kcp;
        }

        public static Kcp Create(KCPSettings kcpSettings, uint conv, KcpCallback output)
        {
            var kcp = new Kcp(conv, output, FANTASY_KCP_RESERVED_HEAD);
            kcp.SetNoDelay(1, 5, 2, 1);
            kcp.SetWindowSize(kcpSettings.SendWindowSize, kcpSettings.ReceiveWindowSize);
            kcp.SetMtu(kcpSettings.Mtu);
            kcp.SetMinrto(30);
            return kcp;
        }
    }
}
#endif