/*
 * Copyright (c) 2017-2018 Rafael da Silva Rocha.
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */

/**
 * @fileoverview Functions to read and write numbers and strings as bytes.
 * @see https://github.com/rochars/byte-data
 */

/** @module byteData */

import endianness from 'endianness';
import {pack as packUTF8, unpack as unpackUTF8} from 'utf8-buffer';
import NumberBuffer from './lib/number-buffer.js';
import {validateIsNumber} from './lib/validation.js';

/**
 * Throw a value error.
 * @throws {Error} A Error with a message based on the input params.
 */
function throwValueError_(e, value, i, fp) {
  if (!fp && (
      value === Infinity || value === -Infinity || value !== value)) {
    throw new Error('Argument is not a integer at input index ' + i);
  } else {
    throw new Error(e.message + ' at input index ' + i + ': ' + value);
  }
}

/**
 * Unpack a array of numbers to a typed array.
 * All other unpacking functions are interfaces to this function.
 * @param {!Uint8Array|!Array<number>} buffer The byte buffer.
 * @param {number=} start The buffer index to start reading.
 * @param {number=} end The buffer index to stop reading.
 * @param {number=} offset The number of bytes used by the type.
 * @param {boolean=} safe True for size-safe buffer reading.
 * @throws {Error} On bad buffer length, if safe.
 */
function getUnpackLen_(buffer, start, end, offset, safe) {
  /** @type {number} */
  let extra = (end - start) % offset;
  if (safe && (extra || buffer.length < offset)) {
    throw new Error('Bad buffer length');
  }
  return end - extra;
}

/**
 * Read a string of UTF-8 characters from a byte buffer.
 * @param {!Uint8Array|!Array<number>} buffer A byte buffer.
 * @param {number=} index The buffer index to start reading.
 * @param {number=} end The buffer index to stop reading, non inclusive.
 *   Assumes buffer length if undefined.
 * @return {string}
 */
export function unpackString(buffer, index=0, end=buffer.length) {
  return unpackUTF8(buffer, index, end);
}

/**
 * Write a string of UTF-8 characters as a byte buffer.
 * @param {string} str The string to pack.
 * @return {!Array<number>} The UTF-8 string bytes.
 */ 
export function packString(str) {
  /** @type {!Array<number>} */
  let buffer = [];
  packUTF8(str, buffer, 0);
  return buffer;
}

/**
 * Write a string of UTF-8 characters to a byte buffer.
 * @param {string} str The string to pack.
 * @param {!Uint8Array|!Array<number>} buffer The output buffer.
 * @param {number=} index The buffer index to start writing.
 *   Assumes zero if undefined.
 * @return {number} The next index to write in the buffer.
 */
export function packStringTo(str, buffer, index=0) {
  return packUTF8(str, buffer, index);
}

// Numbers
/**
 * Pack a array of numbers to a byte buffer.
 * All other packing functions are interfaces to this function.
 * @param {!Array<number>|!TypedArray} values The value.
 * @param {!Object} theType The type definition.
 * @param {!Uint8Array|!Array<number>} buffer The output buffer.
 * @param {number=} index The buffer index to start writing.
 *   Assumes zero if undefined.
 * @return {number} The next index to write.
 * @throws {Error} If the type definition is not valid.
 * @throws {Error} If the value is not valid.
 */
export function packArrayTo(values, theType, buffer, index=0) {
  theType = theType || {};
  /** @type {NumberBuffer} */
  let packer = new NumberBuffer(theType.bits, theType.fp, theType.signed);
  /** @type {number} */
  let i = 0;
  /** @type {number} */
  let start = index;
  try {
    for (let valuesLen = values.length; i < valuesLen; i++) {
      validateIsNumber(values[i]);
      index = packer.pack(buffer, values[i], index);
    }
    if (theType.be) {
      endianness(buffer, packer.offset, start, index);
    }
  } catch (e) {
    throwValueError_(e, values[i], i, theType.fp);
  }
  return index;
}

/**
 * Unpack a array of numbers to a typed array.
 * All other unpacking functions are interfaces to this function.
 * @param {!Uint8Array|!Array<number>} buffer The byte buffer.
 * @param {!Object} theType The type definition.
 * @param {!TypedArray|!Array<number>} output The output array.
 * @param {number=} start The buffer index to start reading.
 *   Assumes zero if undefined.
 * @param {number=} end The buffer index to stop reading.
 *   Assumes the buffer length if undefined.
 * @param {boolean=} safe If set to false, extra bytes in the end of
 *   the array are ignored and input buffers with insufficient bytes will
 *   write nothing to the output array. If safe is set to true the function
 *   will throw a 'Bad buffer length' error. Defaults to false.
 * @throws {Error} If the type definition is not valid
 * @throws {Error} On overflow
 */
export function unpackArrayTo(
    buffer, theType, output, start=0, end=buffer.length, safe=false) {
  theType = theType || {};
  /** @type {NumberBuffer} */
  let packer = new NumberBuffer(theType.bits, theType.fp, theType.signed);
  /** @type {number} */
  let offset = packer.offset;
  // getUnpackLen_ will either fix the length of the input buffer
  // according to the byte offset of the type (on unsafe mode) or
  // throw a Error if the input buffer has a bad length (on safe mode)
  end = getUnpackLen_(buffer, start, end, offset, safe);
  /** @type {number} */
  let index = 0;
  let j = start;
  try {
    if (theType.be) {
      endianness(buffer, offset, start, end);
    }
    for (; j < end; j += offset, index++) {
      output[index] = packer.unpack(buffer, j);
    }
    if (theType.be) {
      endianness(buffer, offset, start, end);
    }
  } catch (e) {
    throwValueError_(e, buffer.slice(j, j + offset), j, theType.fp);
  }
}

/**
 * Pack a number to a byte buffer.
 * @param {number} value The value.
 * @param {!Object} theType The type definition.
 * @param {!Uint8Array|!Array<number>} buffer The output buffer.
 * @param {number=} index The buffer index to write. Assumes 0 if undefined.
 * @return {number} The next index to write.
 * @throws {Error} If the type definition is not valid.
 * @throws {Error} If the value is not valid.
 */
export function packTo(value, theType, buffer, index=0) {
  return packArrayTo([value], theType, buffer, index);
}

/**
 * Pack a number as a byte buffer.
 * @param {number} value The number.
 * @param {!Object} theType The type definition.
 * @return {!Array<number>} The packed value.
 * @throws {Error} If the type definition is not valid.
 * @throws {Error} If the value is not valid.
 */
export function pack(value, theType) {
  /** @type {!Array<number>} */
  let output = [];
  packTo(value, theType, output);
  return output;
}

/**
 * Pack an array of numbers as a byte buffer.
 * @param {!Array<number>|!TypedArray} values The values.
 * @param {!Object} theType The type definition.
 * @return {!Array<number>} The packed values.
 * @throws {Error} If the type definition is not valid.
 * @throws {Error} If any of the values are not valid.
 */
export function packArray(values, theType) {
  /** @type {!Array<number>} */
  let output = [];
  packArrayTo(values, theType, output);
  return output;
}

/**
 * Unpack an array of numbers from a byte buffer.
 * @param {!Uint8Array|!Array<number>} buffer The byte buffer.
 * @param {!Object} theType The type definition.
 * @param {number=} start The buffer index to start reading.
 *   Assumes zero if undefined.
 * @param {number=} end The buffer index to stop reading.
 *   Assumes the buffer length if undefined.
 * @param {boolean=} safe If set to false, extra bytes in the end of
 *   the array are ignored and input buffers with insufficient bytes will
 *   output a empty array. If safe is set to true the function
 *   will throw a 'Bad buffer length' error. Defaults to false.
 * @return {!Array<number>}
 * @throws {Error} If the type definition is not valid
 * @throws {Error} On overflow
 */
export function unpackArray(
    buffer, theType, start=0, end=buffer.length, safe=false) {
  /** @type {!Array<number>} */
  let output = [];
  unpackArrayTo(buffer, theType, output, start, end, safe);
  return output;
}

/**
 * Unpack a number from a byte buffer.
 * @param {!Uint8Array|!Array<number>} buffer The byte buffer.
 * @param {!Object} theType The type definition.
 * @param {number=} index The buffer index to read. Assumes zero if undefined.
 * @return {number}
 * @throws {Error} If the type definition is not valid
 * @throws {Error} On bad buffer length.
 * @throws {Error} On overflow
 */
export function unpack(buffer, theType, index=0) {
  return unpackArray(
    buffer, theType, index, index + Math.ceil(theType.bits / 8), true)[0];
}
