using Edge.Core.Parser.BinaryParser;
using Edge.Core.Parser.BinaryParser.MessageEntity;
using Edge.Core.Parser.BinaryParser.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace LanTian_Sinopec_PumpIcCardReader
{
    public class MessageTemplateLookup : IMessageTemplateLookup
    {
        /// <summary>
        /// Gets the default singleton instance of type MessageTemplateLookup.
        /// </summary>
        public static MessageTemplateLookup Default { get; } = new MessageTemplateLookup();

        /// <summary>
        /// </summary>
        /// <param name="bytes">whole message raw bytes</param>
        /// <returns>new created message entity</returns>
        public MessageTemplateBase GetMessageTemplateByRawBytes(byte[] bytes)
        {
            // from protocol definition, the msg body started at 7th byte, and the 7th bytes is always the msg type code.
            var msgHandleCode = bytes.Skip(6).First();
            switch (msgHandleCode)
            {
                //case 0x30:
                //    return new PumpGenericInquiryCommand();
                case 0x31:
                    return new PumpRealTimeStateEvent();
                case 0x32:
                    if (bytes.Length > 12)
                        return new PumpNotifyTransactionDoneRequest();
                    else
                        return new PcReadTransactionButDoesNotFindResponse();
                case 0x33:
                    return new PumpAskDataDownloadRequest();
                case 0x35:
                    return new PumpInquiryGrayCardRecordRequest();
                case 0x36:
                    return new PumpInquiryBlackAndWhiteListRequest();
                case 0x3A:
                    return new PcReadPumpInfoResponse();
                case 0x3B:
                    return new PumpInternalErrorRequest();

                case 0x50:
                    return new PumpInquiryCreditCardRecordRequest();
            }

            throw new ArgumentException("Can't find correlated message entity type for incoming raw message bytes: " + bytes.Select(s => s.ToString("X").PadLeft(2, '0')).Aggregate((n, acc) => n + " " + acc));
        }
    }
}