"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _datetimen = _interopRequireDefault(require("./datetimen"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

const EPOCH_DATE = new Date(1900, 0, 1);
const UTC_EPOCH_DATE = new Date(Date.UTC(1900, 0, 1));
const DateTime = {
  id: 0x3D,
  type: 'DATETIME',
  name: 'DateTime',
  declaration: function declaration() {
    return 'datetime';
  },
  writeTypeInfo: function writeTypeInfo(buffer) {
    buffer.writeUInt8(_datetimen.default.id);
    buffer.writeUInt8(8);
  },
  // ParameterData<any> is temporary solution. TODO: need to understand what type ParameterData<...> can be.
  writeParameterData: function writeParameterData(buffer, parameter, options, cb) {
    if (parameter.value != null) {
      let days, dstDiff, milliseconds, seconds, threeHundredthsOfSecond;

      if (options.useUTC) {
        days = Math.floor((parameter.value.getTime() - UTC_EPOCH_DATE.getTime()) / (1000 * 60 * 60 * 24));
        seconds = parameter.value.getUTCHours() * 60 * 60;
        seconds += parameter.value.getUTCMinutes() * 60;
        seconds += parameter.value.getUTCSeconds();
        milliseconds = seconds * 1000 + parameter.value.getUTCMilliseconds();
      } else {
        dstDiff = -(parameter.value.getTimezoneOffset() - EPOCH_DATE.getTimezoneOffset()) * 60 * 1000;
        days = Math.floor((parameter.value.getTime() - EPOCH_DATE.getTime() + dstDiff) / (1000 * 60 * 60 * 24));
        seconds = parameter.value.getHours() * 60 * 60;
        seconds += parameter.value.getMinutes() * 60;
        seconds += parameter.value.getSeconds();
        milliseconds = seconds * 1000 + parameter.value.getMilliseconds();
      }

      threeHundredthsOfSecond = milliseconds / (3 + 1 / 3);
      threeHundredthsOfSecond = Math.round(threeHundredthsOfSecond); // 25920000 equals one day

      if (threeHundredthsOfSecond === 25920000) {
        days += 1;
        threeHundredthsOfSecond = 0;
      }

      buffer.writeUInt8(8);
      buffer.writeInt32LE(days);
      buffer.writeUInt32LE(threeHundredthsOfSecond);
    } else {
      buffer.writeUInt8(0);
    }

    cb();
  },
  // TODO: type 'any' needs to be revisited.
  validate: function validate(value) {
    if (value == null) {
      return null;
    }

    if (!(value instanceof Date)) {
      value = new Date(Date.parse(value));
    }

    if (isNaN(value)) {
      return new TypeError('Invalid date.');
    }

    return value;
  }
};
var _default = DateTime;
exports.default = _default;
module.exports = DateTime;