using PlcSiemens.O;
using PlcSiemens.Protocol.Common;

namespace PlcSiemens.Protocol.DateTime
{
    public class DateTimeData
    {
        public byte Ret { get; set; }//0xFF
        public byte Size { get; set; }
        public ushort Length { get; set; }
        public byte Rsvd { get; set; }
        public byte HiYear { get; set; }
        public byte[] Time { get; set; }//³€ΆΘ8

        public ushort PacketLength
        { get { return 0x0E; } }

        public DateTimeData()
        {
            Time = new byte[8];
        }

        public void Build(ByteBuffer buffer)
        {
            Ret = buffer.PopByte();
            Size = buffer.PopByte();
            Length = buffer.PopUshort();
            Rsvd = buffer.PopByte();
            HiYear = buffer.PopByte();
            Time = buffer.PopBytes(8);
        }

        public void Build(System.DateTime dt)
        {
            Ret = 0xFF;
            Size = (byte)TsType.TsResOctet;
            Length = 0x000A;
            Rsvd = 0x00;
            HiYear = 0x19; // *must* be 19 tough it's not the Hi part of the year...

            Time[0] = WordToBcd((ushort)(dt.Year - 2000));
            Time[1] = WordToBcd((ushort)(dt.Month));
            Time[2] = WordToBcd((ushort)(dt.Day));
            Time[3] = WordToBcd((ushort)(dt.Hour));
            Time[4] = WordToBcd((ushort)(dt.Minute));
            Time[5] = WordToBcd((ushort)(dt.Second));
            Time[6] = 0x00;
            Time[7] = WordToBcd((ushort)(dt.DayOfWeek));
        }

        public void GetByteBuffer(ByteBuffer buffer)
        {
            buffer.Push(Ret);
            buffer.Push(Size);
            buffer.Push(Length);
            buffer.Push(Rsvd);
            buffer.Push(HiYear);
            buffer.Push(Time);
        }

        private static byte WordToBcd(ushort value)
        {
            return (byte)(((value / 10) << 4) | (value % 10));
        }
    }
}
