using PlcSiemens.O;
using PlcSiemens.Protocol.Header;

namespace PlcSiemens.Protocol.DateTime
{
    public class GetDateTimeResponse : IBuildResponse
    {
        public HeaderPacket Header { get; set; }
        public ParamsResponse Params { get; set; }
        public DateTimeData Data { get; set; }

        public GetDateTimeResponse()
        {
            Header = new HeaderPacket();
            Params = new ParamsResponse();
            Data = new DateTimeData();
        }

        public void Build(ByteBuffer buffer)
        {
            Header.Build(buffer);
            Params.Build(buffer);
            Data.Build(buffer);
        }

        private int BcDtoByte(byte B)
        {
            return ((B >> 4) * 10) + (B & 0x0F);
        }

        public System.DateTime GetDateTime()
        {
            var year = BcDtoByte(Data.Time[0]);
            if (year < 90)
                year = year + 2000;
            var mon = BcDtoByte(Data.Time[1]);
            var day = BcDtoByte(Data.Time[2]);
            var hour = BcDtoByte(Data.Time[3]);
            var min = BcDtoByte(Data.Time[4]);
            var sec = BcDtoByte(Data.Time[5]);
            var wday = (Data.Time[7] & 0x0F);
            System.DateTime dt = new System.DateTime(year, mon, day, hour, min, sec, wday);

            return dt;
        }
    }
}
