using CommonLang;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace XmdsBattleClientBot.Bot
{
    public class ThreadBotClient : BotClient
    {
        private System.Threading.Timer update_timer;
        private long last_update_time;

        public override bool IsRunning { get { return update_timer != null; } }
        public override string RoleName { get { return base.RoleName; } }

        public ThreadBotClient(string user, string pswd, BotConfig cfg)
            : base(user, pswd, cfg, null)
        {
        }

        public override void Start()
        {
            lock (this)
            {
                if (update_timer == null)
                {
                    base.Start();
                    this.last_update_time = CUtils.CurrentTimeMS;
                    this.update_timer = new System.Threading.Timer(do_update, this,
                        1000 / Config.ClientFPS,
                        1000 / Config.ClientFPS);
                }
            }
        }
        public override void Stop()
        {
            lock (this)
            {
                if (update_timer != null)
                {
                    base.Stop();
                    update_timer.Dispose();
                    update_timer = null;
                }
            }
        }

        private void do_update(object state)
        {
            lock (this)
            {
                long curTime = CommonLang.CUtils.CurrentTimeMS;
                if (last_update_time == 0)
                {
                    last_update_time = curTime;
                }
                int intervalMS = (int)(curTime - last_update_time);
                last_update_time = curTime;
                this.Update(intervalMS);
            }
        }

        public override void Update(int intervalMS)
        {
            lock (this)
            {
                base.Update(intervalMS);
            }
        }

    }
}