using CommonAI.ZoneClient;
using CommonLang;
using CommonLang.Concurrent;
using CommonLang.Property;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using XmdsBattleClientBot.Bot;

namespace XmdsBotTest.Runner
{
    public class ModuleChat : BotRunner.RunnerModule
    {
        private static AtomicInteger s_index = new AtomicInteger(0);
        private static List<string> s_chat_list = new List<string>();
        static ModuleChat()
        {
            var all = File.ReadAllLines(Application.StartupPath + @"\ChatData.txt");
            foreach (var line in all)
            {
                if (line.Trim().Length > 0)
                {
                    var kv = line.Split(new char[] { ':' }, 2);
                    if (kv.Length == 2)
                    {
                        s_chat_list.Add(kv[1]);
                    }
                    else
                    {
                        s_chat_list.Add(line);
                    }
                }
            }
        }

        public ModuleChat(BotRunner r) : base(r)
        {
        }

        protected internal override void OnBattleActorReady(ZoneLayer layer, ZoneActor actor)
        {
            layer.AddTimePeriodicMS(Config.ChatIntervalMS, (t) =>
            {
                if (Enable)
                {
                    on_do_1s(layer);
                }
            });
        }

        private void on_do_1s(ZoneLayer layer)
        {
            ThreadPool.QueueUserWorkItem((state) =>
            {
                var text = /*s_index.IncrementAndGet().ToString() + " - " + */CUtils.GetRandomInArray(s_chat_list, bot.Random);
                try
                {
                    var channel = CUtils.GetRandomInArray(Config.ChatChannels, bot.Random);
                    bot.chat_SendChat((err, rsp) =>
                    {
                        if (err != null) log.Error("SentChat : " + err.Message);
                        else log.Info("SentChat : " + rsp);
                    }, text, "", channel);
                }
                catch (Exception err)
                {
                    log.Error(err.Message, err);
                }
            }, bot);
        }

        [Desc("聊天配置")]
        [Expandable]
        public class Config
        {
            [Desc("聊天发送间隔")]
            public static int ChatIntervalMS = 5000;
            [Desc("聊天发送频道")]
            public static BotClient.ChatChannel[] ChatChannels = new BotClient.ChatChannel[]
            {
                 BotClient.ChatChannel.WORLD,
                 BotClient.ChatChannel.NEARBY,
                 BotClient.ChatChannel.ZONE,
            };
            public override string ToString()
            {
                return "聊天配置";
            }
        }
    }
}