using System;
using System.IO;

namespace skyscraper5.Skyscraper.IO
{
    public static class En300468AnnexCDateTime
    {
        public static DateTime? ReadEtsiEn300468AnnexCDateTime(this Stream s)
        {
            return ReadDateTime(s.ReadBytes(5));
        }
        public static DateTime? ReadDateTime(byte[] buffer)
        {
            if (buffer.Length != 5)
                throw new ArgumentException("need 5 bytes");

            (buffer[1], buffer[0]) = (buffer[0], buffer[1]);
            int mjd = BitConverter.ToUInt16(buffer, 0);
            int y1 = (int)(((double)mjd - 15078.2) / 365.25);
            int m1 = (int)((mjd - 14956.1 - (int)((double)y1 * 365.25)) / 30.6001);
            int d = mjd - 14956 - (int)((double)y1 * 365.25) - (int)((double)m1 * 30.6001);
            int k = 0;
            if (m1 == 14 || m1 == 15)
                k = 1;
            int y = y1 + k + 1900;
            int m = m1 - 1 - k * 12;

            m1--;

            int hour = (int)buffer[2].UnpackBcd();
            int minute = (int)buffer[3].UnpackBcd();
            int second = (int)buffer[4].UnpackBcd();

            if (minute > 60)
                return null;

            if (m == -1)
                return null;

            if (m < 0)
                return null;

            return new DateTime(y, m, d, hour, minute, second);
        }

        /*
         * 

        int mjd = payload.getShort() & 0xffff;
        int y1 = (int)(((double)mjd - 15078.2) / 365.25);
        int m1 = (int)((mjd - 14956.1 - (int)((double)y1 * 365.25)) / 30.6001);
        int d = mjd - 14956 - (int)((double)y1 * 365.25) - (int)((double)m1 * 30.6001);
        int k = 0;
        if (m1 == 14 || m1 == 15)
            k = 1;
        int y = y1 + k + 1900;
        int m = m1 - 1 - k * 12;

        byte ho = payload.get();
        String hourString = singleByteToHex(ho);
        if (hourString.contains("A") | hourString.contains("B") | hourString.contains("C") | hourString.contains("D") | hourString.contains("E") | hourString.contains("F"))
            return null;
        int hour = Integer.parseInt(hourString);
        byte mi = payload.get();
        String minuteString = singleByteToHex(mi);
        if (minuteString.contains("A") | minuteString.contains("B") | minuteString.contains("C") | minuteString.contains("D") | minuteString.contains("E") | minuteString.contains("F"))
            return null;
        int minute = Integer.parseInt(minuteString);
        byte se = payload.get();
        String secondString = singleByteToHex(se);
        if (secondString.contains("A") | secondString.contains("B") | secondString.contains("C") | secondString.contains("D") | secondString.contains("E") | secondString.contains("F"))
            return null;
        int second = Integer.parseInt(secondString);

        Date time = new GregorianCalendar(y, m - 1, d, hour, minute, second).getTime();
        return time;
         */
    }
}
