using PlcSiemens.Core.Extension;
using PlcSiemens.O;
using PlcSiemens.Protocol.Common;
using PlcSiemens.Protocol.ReadData;

namespace PlcSiemens.Protocol.WriteData
{
    public class WriteParamsRequest
    {
        public byte FunRead { get; set; }
        public byte ItemsCount { get; set; }
        public WriteItemRequest[] Items { get; set; }//最大长度20

        public byte PacketLength
        {
            get
            {
                return (byte)(0x0C * Items.Length + 2);
            }
        }

        public WriteParamsRequest()
        {
        }

        public void Build(List<DataItem> dataItems)
        {
            FunRead = (byte)PduFuncType.PduFuncWrite;
            ItemsCount = (byte)dataItems.Count;
            //项处理
            Items = new WriteItemRequest[ItemsCount];

            for (var i = 0; i < dataItems.Count; i++)
            {
                var dataItem = dataItems[i];
                var item = new WriteItemRequest();
                Items[i] = item;

                item.ItemHead[0] = 0x12;
                item.ItemHead[1] = 0x0A;
                item.ItemHead[2] = 0x10;
                item.TransportSize = (byte)dataItem.DataType;
                item.Length = dataItem.Length;
                if (dataItem.AreaType == AreaType.DB)
                    item.DB = dataItem.Db;
                else
                    item.DB = 0x0000;

                item.Area = (byte)dataItem.AreaType;
                //ushort address;
                long address;//修改
                if ((dataItem.DataType == DataType.Bit) || (dataItem.DataType == DataType.Counter) || (dataItem.DataType == DataType.Timer))
                    address = dataItem.Start;
                else
                    //address = (ushort)(dataItem.Start * 8);
                    address = (dataItem.Start * 8);//修改

                item.Address[2] = (byte)(address & 0x000000FF);
                address = (ushort)(address >> 8);
                item.Address[1] = (byte)(address & 0x000000FF);
                address = (ushort)(address >> 8);
                item.Address[0] = (byte)(address & 0x000000FF);
            }
        }

        public void GetByteBuffer(ByteBuffer buffer)
        {
            buffer.Push(FunRead);
            buffer.Push(ItemsCount);

            Items.ForEach(t =>
            {
                buffer.Push(t.ItemHead);
                buffer.Push(t.TransportSize);
                buffer.Push(t.Length);
                buffer.Push(t.DB);
                buffer.Push(t.Area);
                buffer.Push(t.Address);
            });
        }
    }
}
