using Communicator;
using log4net;
using Parser.BinaryParser.Util;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WayneChina_IcCardReader_SinoChem
{
    public class StateMachineMessageCutter : IMessageCutter<byte[]>
    {
        public byte[] Message { get; private set; }

        public event EventHandler OnMessageCut;

        static ILog innerLogger = log4net.LogManager.GetLogger("StateMachineMessageCutter");
        private string loggerAppendix = "WayneChina_IcCardReader_SinoChem msgCutter ";
        private readonly SizableWindow<byte> window;
        private State nextState = State.Uninitialized;

        /// <summary>
        /// if the 0xFA count is odd, will use round up for count/2.
        /// e.g.: 0xFA appeared 2 times, return 1.
        /// 0xFA appeared 3 times, return 2, this is considered as window is not big enough to include further 0xFA since they're always even.
        /// </summary>
        /// <returns></returns>
        private int Get0xFAPairCountInWindow(IList<byte> target)
        {
            return (int)Math.Round(((double)(target.Count(w => w == 0xFA)) / 2), MidpointRounding.AwayFromZero);
        }

        /// <summary>
        /// found all pair(one besides one) of 0xFA in a list, and reduce the pair to a single 0xFA.
        /// </summary>
        /// <param name="target"></param>
        private int Reduce0xFAPair(IList<byte> target, int from)
        {
            var faAppearedPositions = new List<int>();
            for (int i = from; i < target.Count; i++)
            {
                if (target[i] == 0xFA)
                {
                    faAppearedPositions.Add(i);
                    i++;
                }
            }

            for (int i = 0; i < faAppearedPositions.Count; i++)
            {
                target.RemoveAt(faAppearedPositions[i] - i);
            }

            return faAppearedPositions.Count;
        }
        /// <summary>
        /// 
        /// </summary>
        public StateMachineMessageCutter()
        {
            //通讯数据包格式为:数据包头(0xFA)+源地址(1byte)+有效数据长度(2 bytes)+有效数据+数据校验(2 bytes)
            this.window = new SizableWindow<byte>();
            this.window.OnWindowFull += (data) =>
            {
                switch (nextState)
                {
                    case State.Uninitialized:
                        if (data.First() == 0xFA)
                        {
                            // extend to 2 to see if exists extra 0xFA
                            this.window.NewSize = 2;
                            this.nextState = State.PrefixReady;
                            innerLogger.Debug(this.loggerAppendix + " state is State.Uninitialized and next is 0xFF, switch to LengthReady");
                        }
                        else
                            this.window.Clear();
                        break;
                    case State.PrefixReady:
                        if (this.window.Count(h => h == 0xFA) == 1)
                        {
                            innerLogger.Debug(this.loggerAppendix + " 1 time of 0xFA in header window, valid starter, switch to LengthReady");
                            this.nextState = State.LengthReady;
                            this.window.NewSize = 4;
                        }
                        else
                        {
                            innerLogger.Debug(this.loggerAppendix + " 2 times of 0xFA in potential header window, drop all and wait...");
                            // double 0xFA, not a starter.
                            this.nextState = State.Uninitialized;
                            this.window.Clear();
                        }
                        break;
                    case State.LengthReady:
                        //this.DumpWindowToQueue();
                        try
                        {
                            this.window.NewSize += this.window.Skip(2).Take(2).GetBCD();
                            this.nextState = State.BodyReady;
                            innerLogger.Debug(this.loggerAppendix + " MsgBodyLen caculated with: " + this.window.NewSize);
                        }
                        catch (Exception ex)
                        {
                            innerLogger.Debug($"LengthReady: Exception in parsing message length bytes : {ex.ToString()}");
                            this.nextState = State.Uninitialized;
                            this.window.Clear();
                        }

                        break;
                    case State.BodyReady:
                        //innerLogger.Debug(this.loggerAppendix + " Fire OnMessageConstructed with innerQueue: " + this.buffer.ToHexLogString());
                        if (this.window.All(w => w != 0xFA))
                        {
                            innerLogger.Debug(this.loggerAppendix + " MsgBody have NO 0xFA, fastly switch to CrcReady");
                            /* window size exactly match with MsgBodyLen, indicats there's no 0xFA in body.*/
                            this.window.NewSize += 2;
                            this.nextState = State.CrcReady;
                        }
                        else
                        {
                            try
                            {
                                /* window size not match with MsgBodyLen, indicates there's one or more 0xFA in body.*/
                                var __msgBodyLen = this.window.Skip(2).Take(2).GetBCD();
                                var faPairCount = Get0xFAPairCountInWindow(this.window.Skip(1).ToList());
                                if ((this.window.Count - 4) == (__msgBodyLen + faPairCount))
                                {
                                    //innerLogger.Debug(this.loggerAppendix + " Reduce0xFAPair from raw window: " + this.window.ToHexLogString());
                                    var reducedCount = this.Reduce0xFAPair(this.window, 1);
                                    this.window.NewSize += (2 - reducedCount);
                                    this.nextState = State.CrcReady;
                                }
                                else
                                {
                                    /*extend the window based on 0xFA count in `current` window.  NOTE, every extend may include new 0xFA pair.*/
                                    this.window.NewSize += 1;
                                    //innerLogger.Debug(this.loggerAppendix + " Re-extend window size to: " + this.windowSize);
                                }
                            }
                            catch (Exception ex)
                            {
                                innerLogger.Debug($"BodyReady: Exception in parsing message length bytes : {ex.ToString()}");
                                this.nextState = State.Uninitialized;
                                this.window.Clear();
                            }
                        }

                        break;
                    case State.CrcReady:
                        try
                        {
                            var _msgBodyLen = this.window.Skip(2).Take(2).GetBCD();
                            var crcPart = this.window.Skip(4 + _msgBodyLen).ToList();
                            if (crcPart.Count == 2 && crcPart[0] == 0xFA)
                            {
                                innerLogger.Debug(this.loggerAppendix + " Crc[0] is 0xFA, extend windowSize to 3");
                                this.window.NewSize += 1; return;
                            }
                            if (crcPart.Count == 3 && crcPart[2] == 0xFA)
                            {
                                innerLogger.Debug(this.loggerAppendix + " Crc[2] is 0xFA, extend windowSize to 4");
                                this.window.NewSize += 1; return;
                            }

                            Enumerable.Repeat("_", (int)Math.Round(((double)(crcPart.Count(w => w == 0xFA)) / 2))).ToList().ForEach(
                                s =>
                                {
                                    innerLogger.Debug(this.loggerAppendix + " Removing one 0xFA from Crc part.");
                                    crcPart.Remove(0xFA);
                                });

                            this.Message = this.window.Take(4 + _msgBodyLen).ToList().Concat(crcPart).ToArray();
                            var safe = this.OnMessageCut;
                            safe?.Invoke(this, null);
                            this.nextState = State.Uninitialized;
                            this.window.Clear();
                            //this.window.NewSize = this.initWindowSize;
                        }
                        catch (Exception ex)
                        {
                            innerLogger.Debug($"CrcReady: BodyReady: Exception in parsing message length bytes : {ex.ToString()}");
                            this.nextState = State.Uninitialized;
                            this.window.Clear();
                        }

                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }
            };
        }

        private enum State
        {
            Uninitialized,
            // single 0xFA
            PrefixReady,
            // 0xFA + 1 byte source address
            HeaderReady,
            // 0xFA + 1 byte source address +  2 bytes real length
            LengthReady,
            // 0xFA + 1 byte source address +  2 bytes real length + real data
            BodyReady,
            // 0xFA + 1 byte source address +  2 bytes real length + real data + 2 bytes CRC
            CrcReady,
        }

        public void Feed(byte[] next)
        {
            //innerLogger.Debug(this.loggerAppendix + " " + next.ToHexLogString() + " is feed in Window in state: " + nextState);
            for (int i = 0; i < next.Length; i++)
                this.window.Add(next[i]);
        }
    }
}