'use strict';

var NULL = (1 << 16) - 1;

module.exports = {
  id: 0xAF,
  type: 'BIGCHAR',
  name: 'Char',
  hasCollation: true,
  dataLengthLength: 2,
  maximumLength: 8000,

  declaration: function declaration(parameter) {
    var length = void 0;
    if (parameter.length) {
      length = parameter.length;
    } else if (parameter.value != null) {
      length = parameter.value.toString().length || 1;
    } else if (parameter.value === null && !parameter.output) {
      length = 1;
    } else {
      length = this.maximumLength;
    }

    if (length < this.maximumLength) {
      return 'char(' + length + ')';
    } else {
      return 'char(' + this.maximumLength + ')';
    }
  },

  resolveLength: function resolveLength(parameter) {
    if (parameter.length != null) {
      return parameter.length;
    } else if (parameter.value != null) {
      if (Buffer.isBuffer(parameter.value)) {
        return parameter.value.length || 1;
      } else {
        return parameter.value.toString().length || 1;
      }
    } else {
      return this.maximumLength;
    }
  },

  writeTypeInfo: function writeTypeInfo(buffer, parameter) {
    buffer.writeUInt8(this.id);
    buffer.writeUInt16LE(parameter.length);
    buffer.writeBuffer(new Buffer([0x00, 0x00, 0x00, 0x00, 0x00]));
  },

  writeParameterData: function writeParameterData(buffer, parameter) {
    if (parameter.value != null) {
      buffer.writeUsVarbyte(parameter.value, 'ascii');
    } else {
      buffer.writeUInt16LE(NULL);
    }
  },

  validate: function validate(value) {
    if (value == null) {
      return null;
    }
    if (typeof value !== 'string') {
      if (typeof value.toString !== 'function') {
        return TypeError('Invalid string.');
      }
      value = value.toString();
    }
    return value;
  }
};