/**
 * negotiator
 * Copyright(c) 2012 Isaac Z. Schlueter
 * Copyright(c) 2014 Federico Romero
 * Copyright(c) 2014-2015 Douglas Christopher Wilson
 * MIT Licensed
 */

'use strict';

/**
 * Module exports.
 * @public
 */

module.exports = preferredMediaTypes;
module.exports.preferredMediaTypes = preferredMediaTypes;

/**
 * Module variables.
 * @private
 */

var simpleMediaTypeRegExp = /^\s*([^\s\/;]+)\/([^;\s]+)\s*(?:;(.*))?$/;

/**
 * Parse the Accept header.
 * @private
 */

function parseAccept(accept) {
  var accepts = splitMediaTypes(accept);

  for (var i = 0, j = 0; i < accepts.length; i++) {
    var mediaType = parseMediaType(accepts[i].trim(), i);

    if (mediaType) {
      accepts[j++] = mediaType;
    }
  }

  // trim accepts
  accepts.length = j;

  return accepts;
}

/**
 * Parse a media type from the Accept header.
 * @private
 */

function parseMediaType(str, i) {
  var match = simpleMediaTypeRegExp.exec(str);
  if (!match) return null;

  var params = Object.create(null);
  var q = 1;
  var subtype = match[2];
  var type = match[1];

  if (match[3]) {
    var kvps = splitParameters(match[3]).map(splitKeyValuePair);

    for (var j = 0; j < kvps.length; j++) {
      var pair = kvps[j];
      var key = pair[0].toLowerCase();
      var val = pair[1];

      // get the value, unwrapping quotes
      var value = val && val[0] === '"' && val[val.length - 1] === '"'
        ? val.substr(1, val.length - 2)
        : val;

      if (key === 'q') {
        q = parseFloat(value);
        break;
      }

      // store parameter
      params[key] = value;
    }
  }

  return {
    type: type,
    subtype: subtype,
    params: params,
    q: q,
    i: i
  };
}

/**
 * Get the priority of a media type.
 * @private
 */

function getMediaTypePriority(type, accepted, index) {
  var priority = {o: -1, q: 0, s: 0};

  for (var i = 0; i < accepted.length; i++) {
    var spec = specify(type, accepted[i], index);

    if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) {
      priority = spec;
    }
  }

  return priority;
}

/**
 * Get the specificity of the media type.
 * @private
 */

function specify(type, spec, index) {
  var p = parseMediaType(type);
  var s = 0;

  if (!p) {
    return null;
  }

  if(spec.type.toLowerCase() == p.type.toLowerCase()) {
    s |= 4
  } else if(spec.type != '*') {
    return null;
  }

  if(spec.subtype.toLowerCase() == p.subtype.toLowerCase()) {
    s |= 2
  } else if(spec.subtype != '*') {
    return null;
  }

  var keys = Object.keys(spec.params);
  if (keys.length > 0) {
    if (keys.every(function (k) {
      return spec.params[k] == '*' || (spec.params[k] || '').toLowerCase() == (p.params[k] || '').toLowerCase();
    })) {
      s |= 1
    } else {
      return null
    }
  }

  return {
    i: index,
    o: spec.i,
    q: spec.q,
    s: s,
  }
}

/**
 * Get the preferred media types from an Accept header.
 * @public
 */

function preferredMediaTypes(accept, provided) {
  // RFC 2616 sec 14.2: no header = */*
  var accepts = parseAccept(accept === undefined ? '*/*' : accept || '');

  if (!provided) {
    // sorted list of all types
    return accepts
      .filter(isQuality)
      .sort(compareSpecs)
      .map(getFullType);
  }

  var priorities = provided.map(function getPriority(type, index) {
    return getMediaTypePriority(type, accepts, index);
  });

  // sorted list of accepted types
  return priorities.filter(isQuality).sort(compareSpecs).map(function getType(priority) {
    return provided[priorities.indexOf(priority)];
  });
}

/**
 * Compare two specs.
 * @private
 */

function compareSpecs(a, b) {
  return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0;
}

/**
 * Get full type string.
 * @private
 */

function getFullType(spec) {
  return spec.type + '/' + spec.subtype;
}

/**
 * Check if a spec has any quality.
 * @private
 */

function isQuality(spec) {
  return spec.q > 0;
}

/**
 * Count the number of quotes in a string.
 * @private
 */

function quoteCount(string) {
  var count = 0;
  var index = 0;

  while ((index = string.indexOf('"', index)) !== -1) {
    count++;
    index++;
  }

  return count;
}

/**
 * Split a key value pair.
 * @private
 */

function splitKeyValuePair(str) {
  var index = str.indexOf('=');
  var key;
  var val;

  if (index === -1) {
    key = str;
  } else {
    key = str.substr(0, index);
    val = str.substr(index + 1);
  }

  return [key, val];
}

/**
 * Split an Accept header into media types.
 * @private
 */

function splitMediaTypes(accept) {
  var accepts = accept.split(',');

  for (var i = 1, j = 0; i < accepts.length; i++) {
    if (quoteCount(accepts[j]) % 2 == 0) {
      accepts[++j] = accepts[i];
    } else {
      accepts[j] += ',' + accepts[i];
    }
  }

  // trim accepts
  accepts.length = j + 1;

  return accepts;
}

/**
 * Split a string of parameters.
 * @private
 */

function splitParameters(str) {
  var parameters = str.split(';');

  for (var i = 1, j = 0; i < parameters.length; i++) {
    if (quoteCount(parameters[j]) % 2 == 0) {
      parameters[++j] = parameters[i];
    } else {
      parameters[j] += ';' + parameters[i];
    }
  }

  // trim parameters
  parameters.length = j + 1;

  for (var i = 0; i < parameters.length; i++) {
    parameters[i] = parameters[i].trim();
  }

  return parameters;
}


'use strict';

var AlgorithmIdentifier = require('./algorithm-identifier');
var Version = require('./version');

module.exports = require('asn1.js').define('PrivateKeyInfo', /* @this */ function() {
	this.seq().obj(
		this.key('version').use(Version),
		this.key('privateKeyAlgorithm').use(AlgorithmIdentifier),
		this.key('privateKey').octstr(),
		this.key('attributes').optional().any()
	);
});


'use strict';

var asn1 = require('asn1.js'),
	Buffer = require('safe-buffer').Buffer,
	EC = require('elliptic').ec;

var b64ToBn = require('./b64-to-bn');

var PublicKeyInfo = require('./asn1/public-key-info'),
	PrivateKeyInfo = require('./asn1/private-key-info'),
	Version = require('./asn1/version');

var ECParameters = asn1.define('ECParameters', /* @this */ function() {
	this.choice({
		namedCurve: this.objid()
	});
});

var ecPrivkeyVer1 = 1;

var ECPrivateKey = asn1.define('ECPrivateKey', /* @this */ function() {
	this.seq().obj(
		this.key('version').use(Version),
		this.key('privateKey').octstr(),
		this.key('parameters').explicit(0).optional().any(),
		this.key('publicKey').explicit(1).optional().bitstr()
	);
});

var curves = {
	'P-256': 'p256',
	'P-384': 'p384',
	'P-521': 'p521'
};

var oids = {
	'P-256': [1, 2, 840, 10045, 3, 1, 7],
	'P-384': [1, 3, 132, 0, 34],
	'P-521': [1, 3, 132, 0, 35]
};
var parameters = {};
var algorithms = {};
Object.keys(oids).forEach(function(crv) {
	parameters[crv] = ECParameters.encode({
		type: 'namedCurve',
		value: oids[crv]
	}, 'der');
	algorithms[crv] = {
		algorithm:  [1, 2, 840, 10045, 2, 1],
		parameters: parameters[crv]
	};
});
oids = null;

function ecJwkToBuffer(jwk, opts) {
	if ('string' !== typeof jwk.crv) {
		throw new TypeError('Expected "jwk.crv" to be a String');
	}

	var hasD = 'string' === typeof jwk.d;
	var xyTypes = hasD
		? ['undefined', 'string']
		: ['string'];

	if (-1 === xyTypes.indexOf(typeof jwk.x)) {
		throw new TypeError('Expected "jwk.x" to be a String');
	}

	if (-1 === xyTypes.indexOf(typeof jwk.y)) {
		throw new TypeError('Expected "jwk.y" to be a String');
	}

	if (opts.private && !hasD) {
		throw new TypeError('Expected "jwk.d" to be a String');
	}

	var curveName = curves[jwk.crv];
	if (!curveName) {
		throw new Error('Unsupported curve "' + jwk.crv + '"');
	}

	var curve = new EC(curveName);

	var key = {};

	var hasPub = jwk.x && jwk.y;
	if (hasPub) {
		key.pub = {
			x: b64ToBn(jwk.x, false),
			y: b64ToBn(jwk.y, false)
		};
	}

	if (opts.private || !hasPub) {
		key.priv = b64ToBn(jwk.d, true);
	}

	key = curve.keyPair(key);

	var keyValidation = key.validate();
	if (!keyValidation.result) {
		throw new Error('Invalid key for curve: "' + keyValidation.reason + '"');
	}

	var result = keyToPem(jwk.crv, key, opts);

	return result;
}

function keyToPem(crv, key, opts) {
	var compact = false;
	var publicKey = key.getPublic(compact, 'hex');
	publicKey = Buffer.from(publicKey, 'hex');
	publicKey = {
		unused: 0,
		data: publicKey
	};

	var result;
	if (opts.private) {
		var privateKey = key.getPrivate('hex');
		privateKey = Buffer.from(privateKey, 'hex');

		result = PrivateKeyInfo.encode({
			version: 0,
			privateKeyAlgorithm: algorithms[crv],
			privateKey: ECPrivateKey.encode({
				version: ecPrivkeyVer1,
				privateKey: privateKey,
				parameters: parameters[crv],
				publicKey: publicKey
			}, 'der')
		}, 'pem', {
			label: 'PRIVATE KEY'
		});

		privateKey.fill(0);
	} else {
		result = PublicKeyInfo.encode({
			algorithm: algorithms[crv],
			PublicKey: publicKey
		}, 'pem', {
			label: 'PUBLIC KEY'
		});
	}

	// This is in an if incase asn1.js adds a trailing \n
	// istanbul ignore else
	if ('\n' !== result.slice(-1)) {
		result += '\n';
	}

	return result;
}

module.exports = ecJwkToBuffer;


'use strict';

var asn1 = require('asn1.js');

var b64ToBn = require('./b64-to-bn');

var PublicKeyInfo = require('./asn1/public-key-info'),
	PrivateKeyInfo = require('./asn1/private-key-info'),
	Version = require('./asn1/version');

var RSAPrivateKey = asn1.define('RSAPrivateKey', /* @this */ function() {
	this.seq().obj(
		this.key('version').use(Version),
		this.key('modulus').int(),
		this.key('publicExponent').int(),
		this.key('privateExponent').int(),
		this.key('prime1').int(),
		this.key('prime2').int(),
		this.key('exponent1').int(),
		this.key('exponent2').int(),
		this.key('coefficient').int()
	);
});

var RSAPublicKey = asn1.define('RSAPublicKey', /* @this */ function() {
	this.seq().obj(
		this.key('modulus').int(),
		this.key('publicExponent').int()
	);
});

var algorithm = {
	algorithm: [1, 2, 840, 113549, 1, 1, 1],
	parameters: [5, 0]
};

function rsaJwkToBuffer(jwk, opts) {
	if ('string' !== typeof jwk.e) {
		throw new TypeError('Expected "jwk.e" to be a String');
	}

	if ('string' !== typeof jwk.n) {
		throw new TypeError('Expected "jwk.n" to be a String');
	}

	if (opts.private) {
		if ('string' !== typeof jwk.d) {
			throw new TypeError('Expected "jwk.d" to be a String');
		}

		if ('string' !== typeof jwk.p) {
			throw new TypeError('Expected "jwk.p" to be a String');
		}

		if ('string' !== typeof jwk.q) {
			throw new TypeError('Expected "jwk.q" to be a String');
		}

		if ('string' !== typeof jwk.dp) {
			throw new TypeError('Expected "jwk.dp" to be a String');
		}

		if ('string' !== typeof jwk.dq) {
			throw new TypeError('Expected "jwk.dq" to be a String');
		}

		if ('string' !== typeof jwk.qi) {
			throw new TypeError('Expected "jwk.qi" to be a String');
		}
	}

	var pem;
	if (opts.private) {
		pem = PrivateKeyInfo.encode({
			version: 0,
			privateKeyAlgorithm: algorithm,
			privateKey: RSAPrivateKey.encode({
				version: 0,
				modulus: b64ToBn(jwk.n, false),
				publicExponent: b64ToBn(jwk.e, false),
				privateExponent: b64ToBn(jwk.d, true),
				prime1: b64ToBn(jwk.p, true),
				prime2: b64ToBn(jwk.q, true),
				exponent1: b64ToBn(jwk.dp, true),
				exponent2: b64ToBn(jwk.dq, true),
				coefficient: b64ToBn(jwk.qi, true)
			}, 'der')
		}, 'pem', {
			label: 'PRIVATE KEY'
		});
	} else {
		pem = PublicKeyInfo.encode({
			algorithm: algorithm,
			PublicKey: {
				unused: 0,
				data: RSAPublicKey.encode({
					modulus: b64ToBn(jwk.n, false),
					publicExponent: b64ToBn(jwk.e, false)
				}, 'der')
			}
		}, 'pem', {
			label: 'PUBLIC KEY'
		});
	}

	// This is in an if incase asn1.js adds a trailing \n
	// istanbul ignore else
	if ('\n' !== pem.slice(-1)) {
		pem += '\n';
	}

	return pem;
}

module.exports = rsaJwkToBuffer;


////////////////////////////////////////////////////////////////////////////////
// -------------------------------------------------------------------------- //
//                                                                            //
//                       (C) 2010-2018 Robot Developers                       //
//                       See LICENSE for licensing info                       //
//                                                                            //
// -------------------------------------------------------------------------- //
////////////////////////////////////////////////////////////////////////////////

"use strict";

//----------------------------------------------------------------------------//
// Exports                                                                    //
//----------------------------------------------------------------------------//

module.exports = function (robot, native)
{
	//----------------------------------------------------------------------------//
	// Segment                                                             Module //
	//----------------------------------------------------------------------------//

	////////////////////////////////////////////////////////////////////////////////

	function Segment()
	{
		// Auto instantiate the Segment
		if (!(this instanceof Segment))
			return new Segment();

		this.valid = false;
		this.base  = 0;
		this.size  = 0;
		this.name  = "";
	}

	////////////////////////////////////////////////////////////////////////////////

	Segment.prototype.contains = function (value)
	{
		// Check for number comparison
		if (typeof value === "number")
		{
			var base = this.base;
			var stop = this.base +
					   this.size;

			return base <= value &&
				   stop >  value;
		}

		throw new TypeError ("Invalid arguments");
	};

	////////////////////////////////////////////////////////////////////////////////

	Segment.prototype.lt = function (value)
	{
		// Check for another segment
		if (value instanceof Segment)
			return this.base < value.base;

		// Check for number comparison
		if (typeof value === "number")
			return this.base < value;

		throw new TypeError ("Invalid arguments");
	};

	////////////////////////////////////////////////////////////////////////////////

	Segment.prototype.gt = function (value)
	{
		// Check for another segment
		if (value instanceof Segment)
			return this.base > value.base;

		// Check for number comparison
		if (typeof value === "number")
			return this.base > value;

		throw new TypeError ("Invalid arguments");
	};

	////////////////////////////////////////////////////////////////////////////////

	Segment.prototype.le = function (value)
	{
		// Check for another segment
		if (value instanceof Segment)
			return this.base <= value.base;

		// Check for number comparison
		if (typeof value === "number")
			return this.base <= value;

		throw new TypeError ("Invalid arguments");
	};

	////////////////////////////////////////////////////////////////////////////////

	Segment.prototype.ge = function (value)
	{
		// Check for another segment
		if (value instanceof Segment)
			return this.base >= value.base;

		// Check for number comparison
		if (typeof value === "number")
			return this.base >= value;

		throw new TypeError ("Invalid arguments");
	};

	////////////////////////////////////////////////////////////////////////////////

	Segment.prototype.eq = function (segment)
	{
		// Verify that segment is valid
		if (!(segment instanceof Segment))
			throw new TypeError ("Invalid arguments");

		return this.valid === segment.valid
			&& this.base  === segment.base
			&& this.size  === segment.size
			&& this.name  === segment.name;
	};

	////////////////////////////////////////////////////////////////////////////////

	Segment.prototype.ne = function (segment)
	{
		// Verify that segment is valid
		if (!(segment instanceof Segment))
			throw new TypeError ("Invalid arguments");

		return this.valid !== segment.valid
			|| this.base  !== segment.base
			|| this.size  !== segment.size
			|| this.name  !== segment.name;
	};

	//----------------------------------------------------------------------------//
	// Constructor                                                         Module //
	//----------------------------------------------------------------------------//

	////////////////////////////////////////////////////////////////////////////////

	function Module (process, name, path, base, size)
	{
		// Auto instantiate the Module
		if (!(this instanceof Module))
		{
			return new Module (process,
				name, path, base, size);
		}

		// Check for any arguments
		if (process === undefined)
		{
			this._valid = false;
			this._name  = "";
			this._path  = "";
			this._base  = 0;
			this._size  = 0;
			this._proc  = robot.Process();
			this._segments = null;
			return;
		}

		// Verify that args are valid
		if (typeof name === "string" &&
			typeof path === "string" &&
			typeof base === "number" &&
			typeof size === "number" &&
			process instanceof robot.Process)
		{
			this._valid = true;
			this._name  = name;
			this._path  = path;
			this._base  = base;
			this._size  = size;
			this._proc  = process;
			this._segments = null;
			return;
		}

		throw new TypeError ("Invalid arguments");
	}

	//----------------------------------------------------------------------------//
	// Functions                                                           Module //
	//----------------------------------------------------------------------------//

	////////////////////////////////////////////////////////////////////////////////

	Module.prototype.isValid    = function() { return this._valid; };
	Module.prototype.getName    = function() { return this._name;  };
	Module.prototype.getPath    = function() { return this._path;  };
	Module.prototype.getBase    = function() { return this._base;  };
	Module.prototype.getSize    = function() { return this._size;  };
	Module.prototype.getProcess = function() { return this._proc;  };

	////////////////////////////////////////////////////////////////////////////////

	Module.prototype.getSegments = function()
	{
		// Check validity of module
		if (!this._valid) return [ ];

		// Check if value available
		if (this._segments === null)
		{
			this._segments = robot.
				Process._getSegments
				(this._proc, this._base);
		}

		// Return the segments
		return this._segments;
	};

	////////////////////////////////////////////////////////////////////////////////

	Module.prototype.contains = function (value)
	{
		// Check for number comparison
		if (typeof value === "number")
		{
			var base = this._base;
			var stop = this._base +
					   this._size;

			return base <= value &&
				   stop >  value;
		}

		throw new TypeError ("Invalid arguments");
	};

	//----------------------------------------------------------------------------//
	// Operators                                                           Module //
	//----------------------------------------------------------------------------//

	////////////////////////////////////////////////////////////////////////////////

	Module.prototype.lt = function (value)
	{
		// Check for another module
		if (value instanceof Module)
			return this._base < value._base;

		// Check for number comparison
		if (typeof value === "number")
			return this._base < value;

		throw new TypeError ("Invalid arguments");
	};

	////////////////////////////////////////////////////////////////////////////////

	Module.prototype.gt = function (value)
	{
		// Check for another module
		if (value instanceof Module)
			return this._base > value._base;

		// Check for number comparison
		if (typeof value === "number")
			return this._base > value;

		throw new TypeError ("Invalid arguments");
	};

	////////////////////////////////////////////////////////////////////////////////

	Module.prototype.le = function (value)
	{
		// Check for another module
		if (value instanceof Module)
			return this._base <= value._base;

		// Check for number comparison
		if (typeof value === "number")
			return this._base <= value;

		throw new TypeError ("Invalid arguments");
	};

	////////////////////////////////////////////////////////////////////////////////

	Module.prototype.ge = function (value)
	{
		// Check for another module
		if (value instanceof Module)
			return this._base >= value._base;

		// Check for number comparison
		if (typeof value === "number")
			return this._base >= value;

		throw new TypeError ("Invalid arguments");
	};

	////////////////////////////////////////////////////////////////////////////////

	Module.prototype.eq = function (module)
	{
		// Verify that module is valid
		if (!(module instanceof Module))
			throw new TypeError ("Invalid arguments");

		return this._valid === module._valid
			&& this._base  === module._base
			&& this._size  === module._size
			&& this._proc .eq (module._proc);
	};

	////////////////////////////////////////////////////////////////////////////////

	Module.prototype.ne = function (module)
	{
		// Verify that module is valid
		if (!(module instanceof Module))
			throw new TypeError ("Invalid arguments");

		return this._valid !== module._valid
			|| this._base  !== module._base
			|| this._size  !== module._size
			|| this._proc .ne (module._proc);
	};

	////////////////////////////////////////////////////////////////////////////////

	Module.Segment = Segment;
	return Module;
};


////////////////////////////////////////////////////////////////////////////////
// -------------------------------------------------------------------------- //
//                                                                            //
//                       (C) 2010-2018 Robot Developers                       //
//                       See LICENSE for licensing info                       //
//                                                                            //
// -------------------------------------------------------------------------- //
////////////////////////////////////////////////////////////////////////////////

"use strict";

//----------------------------------------------------------------------------//
// Exports                                                                    //
//----------------------------------------------------------------------------//

module.exports = function (robot)
{
	//----------------------------------------------------------------------------//
	// Constants                                                                  //
	//----------------------------------------------------------------------------//

	////////////////////////////////////////////////////////////////////////////////

	var CRC32Table =
	[
		0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F,
		0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
		0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2,
		0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
		0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9,
		0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
		0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C,
		0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
		0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423,
		0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
		0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106,
		0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
		0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D,
		0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
		0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950,
		0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
		0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7,
		0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
		0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA,
		0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
		0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81,
		0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,
		0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84,
		0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
		0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB,
		0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
		0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E,
		0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
		0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55,
		0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
		0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28,
		0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
		0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F,
		0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,
		0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242,
		0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
		0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69,
		0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,
		0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC,
		0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
		0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693,
		0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
		0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
	];

	//----------------------------------------------------------------------------//
	// Constructor                                                           Hash //
	//----------------------------------------------------------------------------//

	////////////////////////////////////////////////////////////////////////////////

	function Hash (data)
	{
		// Auto instantiate the Hash
		if (!(this instanceof Hash))
			return new Hash (data);

		this.result = 0;
		if (data !== undefined)
			this.append (data);
	}

	//----------------------------------------------------------------------------//
	// Functions                                                             Hash //
	//----------------------------------------------------------------------------//

	////////////////////////////////////////////////////////////////////////////////

	Hash.prototype.append = function (data)
	{
		if (!(data instanceof Buffer))
			  data = new Buffer (data);

		// Check if length is valid
		var dataLength = data.length;
		if (dataLength === 0) return;

		// Prepare the crc32 value
		var result = ~this.result;
		for (var i = 0; i < dataLength; ++i)
		{
			// Perform the CRC32 hash function
			result = (result >>> 8) ^ CRC32Table
					[(result ^ data[i]) & 0xFF];
		}

		// Write the resulting value
		this.result = ~result >>> 0;
	};

	//----------------------------------------------------------------------------//
	// Operators                                                             Hash //
	//----------------------------------------------------------------------------//

	////////////////////////////////////////////////////////////////////////////////

	Hash.prototype.eq = function (hash)
	{
		// Check for another Hash
		if (hash instanceof Hash)
			return this.result === hash.result;

		// Check for number comparison
		if (typeof hash === "number")
			return this.result === hash;

		throw new TypeError
			("Invalid arguments");
	};

	////////////////////////////////////////////////////////////////////////////////

	Hash.prototype.ne = function (hash)
	{
		// Check for another Hash
		if (hash instanceof Hash)
			return this.result !== hash.result;

		// Check for number comparison
		if (typeof hash === "number")
			return this.result !== hash;

		throw new TypeError
			("Invalid arguments");
	};

	////////////////////////////////////////////////////////////////////////////////

	return Hash;
};


////////////////////////////////////////////////////////////////////////////////
// -------------------------------------------------------------------------- //
//                                                                            //
//                       (C) 2010-2018 Robot Developers                       //
//                       See LICENSE for licensing info                       //
//                                                                            //
// -------------------------------------------------------------------------- //
////////////////////////////////////////////////////////////////////////////////

"use strict";

//----------------------------------------------------------------------------//
// Exports                                                                    //
//----------------------------------------------------------------------------//

module.exports = function (robot)
{
	//----------------------------------------------------------------------------//
	// Constructor                                                           Size //
	//----------------------------------------------------------------------------//

	////////////////////////////////////////////////////////////////////////////////

	function Size (aw, ah)
	{
		// Auto instantiate the Size
		if (!(this instanceof Size))
			return new Size (aw, ah);

		var s = Size.normalize (aw, ah);
		this.w = s.w;
		this.h = s.h;
	}

	//----------------------------------------------------------------------------//
	// Functions                                                             Size //
	//----------------------------------------------------------------------------//

	////////////////////////////////////////////////////////////////////////////////

	Size.prototype.isZero = function()
	{
		return this.w === 0
			&& this.h === 0;
	};

	////////////////////////////////////////////////////////////////////////////////

	Size.prototype.isEmpty = function()
	{
		return this.w === 0
			|| this.h === 0;
	};

	////////////////////////////////////////////////////////////////////////////////

	Size.prototype.toPoint = function()
	{
		return robot.Point
			(this.w, this.h);
	};

	//----------------------------------------------------------------------------//
	// Static                                                                Size //
	//----------------------------------------------------------------------------//

	////////////////////////////////////////////////////////////////////////////////

	Size.normalize = function (aw, ah)
	{
		if (aw instanceof Size)
			return aw;

		if (aw === undefined)
			return { w: 0, h: 0 };

		if (typeof aw   === "object" &&
			typeof aw.w === "number" &&
			typeof aw.h === "number")
			return aw;

		if (typeof aw === "number")
		{
			if (typeof ah === "number")
				return { w: aw, h: ah };
				return { w: aw, h: aw };
		}

		throw new TypeError
			("Invalid arguments");
	};

	//----------------------------------------------------------------------------//
	// Operators                                                             Size //
	//----------------------------------------------------------------------------//

	////////////////////////////////////////////////////////////////////////////////

	Size.prototype.add = function (aw, ah)
	{
		var s = Size.normalize (aw, ah);
		return Size
			(this.w + s.w, this.h + s.h);
	};

	////////////////////////////////////////////////////////////////////////////////

	Size.prototype.sub = function (aw, ah)
	{
		var s = Size.normalize (aw, ah);
		return Size
			(this.w - s.w, this.h - s.h);
	};

	////////////////////////////////////////////////////////////////////////////////

	Size.prototype.eq = function (aw, ah)
	{
		var s = Size.normalize (aw, ah);
		return this.w === s.w
			&& this.h === s.h;
	};

	////////////////////////////////////////////////////////////////////////////////

	Size.prototype.ne = function (aw, ah)
	{
		var s = Size.normalize (aw, ah);
		return this.w !== s.w
			|| this.h !== s.h;
	};

	////////////////////////////////////////////////////////////////////////////////

	return Size;
};


////////////////////////////////////////////////////////////////////////////////
// -------------------------------------------------------------------------- //
//                                                                            //
//                       (C) 2010-2018 Robot Developers                       //
//                       See LICENSE for licensing info                       //
//                                                                            //
// -------------------------------------------------------------------------- //
////////////////////////////////////////////////////////////////////////////////

"use strict";

//----------------------------------------------------------------------------//
// Exports                                                                    //
//----------------------------------------------------------------------------//

module.exports = function (robot, native)
{
	//----------------------------------------------------------------------------//
	// Constructor                                                         Screen //
	//----------------------------------------------------------------------------//

	////////////////////////////////////////////////////////////////////////////////

	function Screen (bounds, usable)
	{
		// Auto instantiate the Screen
		if (!(this instanceof Screen))
			return new Screen (bounds, usable);

		// Check if using defaults
		if (bounds === undefined &&
			usable === undefined)
		{
			this._bounds = robot.Bounds();
			this._usable = robot.Bounds();
			return;
		}

		// Check if assigning bounds values
		if (bounds instanceof robot.Bounds &&
			usable instanceof robot.Bounds)
		{
			this._bounds = bounds;
			this._usable = usable;
			return;
		}

		throw new TypeError ("Invalid arguments");
	}

	//----------------------------------------------------------------------------//
	// Functions                                                           Screen //
	//----------------------------------------------------------------------------//

	////////////////////////////////////////////////////////////////////////////////

	Screen.prototype.getBounds   = function() { return this._bounds;                     };
	Screen.prototype.getUsable   = function() { return this._usable;                     };
	Screen.prototype.isPortrait  = function() { return this._bounds.w <  this._bounds.h; };
	Screen.prototype.isLandscape = function() { return this._bounds.w >= this._bounds.h; };

	//----------------------------------------------------------------------------//
	// Static                                                              Screen //
	//----------------------------------------------------------------------------//

	////////////////////////////////////////////////////////////////////////////////

	Screen._screens = [ ];
	Screen._totalBounds = robot.Bounds();
	Screen._totalUsable = robot.Bounds();

	////////////////////////////////////////////////////////////////////////////////

	Screen.synchronize = function()
	{
		// Perform native screen synchronization
		var result = native.Screen.synchronize();

		this._screens     = result.screens;
		this._totalBounds = result.totalBounds;
		this._totalUsable = result.totalUsable;

		// Convert screen objects into screen classes
		for (var i = 0; i < this._screens.length; ++i)
		{
			this._screens[i] = Screen
				(this._screens[i].bounds,
				 this._screens[i].usable);
		}

		return result.status;
	};

	////////////////////////////////////////////////////////////////////////////////

	Screen.getMain = function()
	{
		// The primary screen is always the first screen object
		return this._screens.length ? this._screens[0] : null;
	};

	////////////////////////////////////////////////////////////////////////////////

	Screen.getList = function() { return this._screens; };

	////////////////////////////////////////////////////////////////////////////////

	Screen.getScreen = function (ax, ay)
	{
		var p;
		// Check if instance of window
		if (ax instanceof robot.Window)
		{
			if (!ax.isValid()) return null;
			p = ax.getBounds().getCenter();
		}

		// Attempt to parse as a regular point
		else p = robot.Point.normalize (ax, ay);

		// Loop through every available screen object
		for (var i = 0; i < this._screens.length; ++i)
		{
			if (this._screens[i]._bounds.containsP
				(p.x, p.y)) return this._screens[i];
		}

		// The primary screen is always the first screen object
		return this._screens.length ? this._screens[0] : null;
	};

	////////////////////////////////////////////////////////////////////////////////

	Screen.grabScreen = function (image, ax, ay, aw, ah, window)
	{
		// Check if argument is native image
		if (!(image instanceof robot.Image))
			throw new TypeError ("Invalid arguments");

		var b = robot.Bounds.
			normalize (ax, ay, aw, ah);

		// Perform native image capture
		return native.Screen.grabScreen
			(image, b.x, b.y, b.w, b.h,
			 arguments[arguments.length - 1]);
	};

	////////////////////////////////////////////////////////////////////////////////

	Screen.getTotalBounds = function() { return this._totalBounds; };
	Screen.getTotalUsable = function() { return this._totalUsable; };

	////////////////////////////////////////////////////////////////////////////////

	Screen. isCompositing = native.Screen. isCompositing;
	Screen.setCompositing = native.Screen.setCompositing;

	////////////////////////////////////////////////////////////////////////////////

	return Screen;
};


////////////////////////////////////////////////////////////////////////////////
// -------------------------------------------------------------------------- //
//                                                                            //
//                       (C) 2010-2018 Robot Developers                       //
//                       See LICENSE for licensing info                       //
//                                                                            //
// -------------------------------------------------------------------------- //
////////////////////////////////////////////////////////////////////////////////

"use strict";

//----------------------------------------------------------------------------//
// Exports                                                                    //
//----------------------------------------------------------------------------//

module.exports = function (robot, native)
{
	//----------------------------------------------------------------------------//
	// Stats                                                               Memory //
	//----------------------------------------------------------------------------//

	////////////////////////////////////////////////////////////////////////////////

	function Stats()
	{
		// Auto instantiate the Stats
		if (!(this instanceof Stats))
			return new Stats();

		this.systemReads  = 0;
		this.cachedReads  = 0;
		this.systemWrites = 0;
		this.accessWrites = 0;

		this. readErrors  = 0;
		this.writeErrors  = 0;
	}

	////////////////////////////////////////////////////////////////////////////////

	Stats.prototype.eq = function (stats)
	{
		// Verify that stats is valid
		if (!(stats instanceof Stats))
			throw new TypeError ("Invalid arguments");

		return this.systemReads  === stats.systemReads
			&& this.cachedReads  === stats.cachedReads
			&& this.systemWrites === stats.systemWrites
			&& this.accessWrites === stats.accessWrites

			&& this. readErrors  === stats. readErrors
			&& this.writeErrors  === stats.writeErrors;
	};

	////////////////////////////////////////////////////////////////////////////////

	Stats.prototype.ne = function (stats)
	{
		// Verify that stats is valid
		if (!(stats instanceof Stats))
			throw new TypeError ("Invalid arguments");

		return this.systemReads  !== stats.systemReads
			|| this.cachedReads  !== stats.cachedReads
			|| this.systemWrites !== stats.systemWrites
			|| this.accessWrites !== stats.accessWrites

			|| this. readErrors  !== stats. readErrors
			|| this.writeErrors  !== stats.writeErrors;
	};

	//----------------------------------------------------------------------------//
	// Region                                                              Memory //
	//----------------------------------------------------------------------------//

	////////////////////////////////////////////////////////////////////////////////

	function Region()
	{
		// Auto instantiate the Region
		if (!(this instanceof Region))
			return new Region();

		this.valid      = false;
		this.bound      = false;

		this.start      = 0;
		this.stop       = 0;
		this.size       = 0;

		this.readable   = false;
		this.writable   = false;
		this.executable = false;
		this.access     = 0;

		this.private    = false;
		this.guarded    = false;
	}

	////////////////////////////////////////////////////////////////////////////////

	Region.prototype.contains = function (value)
	{
		// Check for number comparison
		if (typeof value === "number")
		{
			return this.start <= value &&
				   this.stop  >  value;
		}

		throw new TypeError ("Invalid arguments");
	};

	////////////////////////////////////////////////////////////////////////////////

	Region.prototype.lt = function (value)
	{
		// Check for another region
		if (value instanceof Region)
			return this.start < value.start;

		// Check for number comparison
		if (typeof value === "number")
			return this.start < value;

		throw new TypeError ("Invalid arguments");
	};

	////////////////////////////////////////////////////////////////////////////////

	Region.prototype.gt = function (value)
	{
		// Check for another region
		if (value instanceof Region)
			return this.start > value.start;

		// Check for number comparison
		if (typeof value === "number")
			return this.start > value;

		throw new TypeError ("Invalid arguments");
	};

	////////////////////////////////////////////////////////////////////////////////

	Region.prototype.le = function (value)
	{
		// Check for another region
		if (value instanceof Region)
			return this.start <= value.start;

		// Check for number comparison
		if (typeof value === "number")
			return this.start <= value;

		throw new TypeError ("Invalid arguments");
	};

	////////////////////////////////////////////////////////////////////////////////

	Region.prototype.ge = function (value)
	{
		// Check for another region
		if (value instanceof Region)
			return this.start >= value.start;

		// Check for number comparison
		if (typeof value === "number")
			return this.start >= value;

		throw new TypeError ("Invalid arguments");
	};

	////////////////////////////////////////////////////////////////////////////////

	Region.prototype.eq = function (region)
	{
		// Verify that region is valid
		if (!(region instanceof Region))
			throw new TypeError ("Invalid arguments");

		return this.valid      === region.valid
			&& this.bound      === region.bound

			&& this.start      === region.start
			&& this.stop       === region.stop
			&& this.size       === region.size

			&& this.readable   === region.readable
			&& this.writable   === region.writable
			&& this.executable === region.executable
			&& this.access     === region.access

			&& this.private    === region.private
			&& this.guarded    === region.guarded;
	};

	////////////////////////////////////////////////////////////////////////////////

	Region.prototype.ne = function (region)
	{
		// Verify that region is valid
		if (!(region instanceof Region))
			throw new TypeError ("Invalid arguments");

		return this.valid      !== region.valid
			|| this.bound      !== region.bound

			|| this.start      !== region.start
			|| this.stop       !== region.stop
			|| this.size       !== region.size

			|| this.readable   !== region.readable
			|| this.writable   !== region.writable
			|| this.executable !== region.executable
			|| this.access     !== region.access

			|| this.private    !== region.private
			|| this.guarded    !== region.guarded;
	};

	//----------------------------------------------------------------------------//
	// Functions                                                           Memory //
	//----------------------------------------------------------------------------//

	////////////////////////////////////////////////////////////////////////////////

	native.Memory.prototype.setAccess = function (region, r, w, x)
	{
		// Verify that region is valid
		if (!(region instanceof Region))
			throw new TypeError ("Invalid arguments");

		return this._setAccess
			// Optimize the native call
			(region.valid, region.bound,
			 region.start, region.size,
			 r, w, x);
	};

	////////////////////////////////////////////////////////////////////////////////

	native.Memory.prototype.getPtrSize    = function() { return this._ptrSize;    };
	native.Memory.prototype.getMinAddress = function() { return this._minAddress; };
	native.Memory.prototype.getMaxAddress = function() { return this._maxAddress; };
	native.Memory.prototype.getPageSize   = function() { return this._pageSize;   };

	//----------------------------------------------------------------------------//
	// Extensions                                                          Memory //
	//----------------------------------------------------------------------------//

	////////////////////////////////////////////////////////////////////////////////

	native.Memory.prototype.readInt8 = function (address, count, stride)
	{
		return this._readType (address, native.Memory._TYPE_INT8, 1, count, stride);
	};

	////////////////////////////////////////////////////////////////////////////////

	native.Memory.prototype.readInt16 = function (address, count, stride)
	{
		return this._readType (address, native.Memory._TYPE_INT16, 2, count, stride);
	};

	////////////////////////////////////////////////////////////////////////////////

	native.Memory.prototype.readInt32 = function (address, count, stride)
	{
		return this._readType (address, native.Memory._TYPE_INT32, 4, count, stride);
	};

	////////////////////////////////////////////////////////////////////////////////

	native.Memory.prototype.readInt64 = function (address, count, stride)
	{
		return this._readType (address, native.Memory._TYPE_INT64, 8, count, stride);
	};

	////////////////////////////////////////////////////////////////////////////////

	native.Memory.prototype.readReal32 = function (address, count, stride)
	{
		return this._readType (address, native.Memory._TYPE_REAL32, 4, count, stride);
	};

	////////////////////////////////////////////////////////////////////////////////

	native.Memory.prototype.readReal64 = function (address, count, stride)
	{
		return this._readType (address, native.Memory._TYPE_REAL64, 8, count, stride);
	};

	////////////////////////////////////////////////////////////////////////////////

	native.Memory.prototype.readPtr = function (address, count, stride)
	{
		if (this._ptrSize === 4)
			return this._readType (address, native.Memory._TYPE_INT32, 4, count, stride);
		else
			return this._readType (address, native.Memory._TYPE_INT64, 8, count, stride);
	};

	////////////////////////////////////////////////////////////////////////////////

	native.Memory.prototype.readBool = function (address, count, stride)
	{
		return this._readType (address, native.Memory._TYPE_BOOL, 1, count, stride);
	};

	////////////////////////////////////////////////////////////////////////////////

	native.Memory.prototype.readString = function (address, length, count, stride)
	{
		return this._readType (address, native.Memory._TYPE_STRING, length, count, stride);
	};

	////////////////////////////////////////////////////////////////////////////////

	native.Memory.prototype.writeInt8 = function (address, data)
	{
		return this._writeType (address, data, native.Memory._TYPE_INT8, 1);
	};

	////////////////////////////////////////////////////////////////////////////////

	native.Memory.prototype.writeInt16 = function (address, data)
	{
		return this._writeType (address, data, native.Memory._TYPE_INT16, 2);
	};

	////////////////////////////////////////////////////////////////////////////////

	native.Memory.prototype.writeInt32 = function (address, data)
	{
		return this._writeType (address, data, native.Memory._TYPE_INT32, 4);
	};

	////////////////////////////////////////////////////////////////////////////////

	native.Memory.prototype.writeInt64 = function (address, data)
	{
		return this._writeType (address, data, native.Memory._TYPE_INT64, 8);
	};

	////////////////////////////////////////////////////////////////////////////////

	native.Memory.prototype.writeReal32 = function (address, data)
	{
		return this._writeType (address, data, native.Memory._TYPE_REAL32, 4);
	};

	////////////////////////////////////////////////////////////////////////////////

	native.Memory.prototype.writeReal64 = function (address, data)
	{
		return this._writeType (address, data, native.Memory._TYPE_REAL64, 8);
	};

	////////////////////////////////////////////////////////////////////////////////

	native.Memory.prototype.writePtr = function (address, data)
	{
		if (this._ptrSize === 4)
			return this._writeType (address, data, native.Memory._TYPE_INT32, 4);
		else
			return this._writeType (address, data, native.Memory._TYPE_INT64, 8);
	};

	////////////////////////////////////////////////////////////////////////////////

	native.Memory.prototype.writeBool = function (address, data)
	{
		return this._writeType (address, data, native.Memory._TYPE_BOOL, 1);
	};

	////////////////////////////////////////////////////////////////////////////////

	native.Memory.prototype.writeString = function (address, data, length)
	{
		return this._writeType (address, data, native.Memory._TYPE_STRING, length);
	};

	////////////////////////////////////////////////////////////////////////////////

	native.Memory.Stats  = Stats;
	native.Memory.Region = Region;
	return native.Memory;
};


var path = require('path');

module.exports = function(config) {
  config.set({
    basePath: '.',

    frameworks: ['jasmine'],
    browsers: ['PhantomJS'],

    files: [
      'node_modules/es5-shim/es5-shim.js',
      'node_modules/react/dist/react.js',
      'node_modules/react/dist/react-with-addons.js',

      'spec/**.spec.jsx',
      { pattern: 'lib/**/*', watched: true, included: false }
    ],

    reporters: ['progress', 'coverage'],

    preprocessors: {
      // add webpack as preprocessor
      'spec/**.spec.jsx': ['webpack', 'sourcemap', 'eslint']
    },

    webpack: loadWebpackConfig(),

    webpackServer: {
      noInfo: true
    },

    eslint: {
      stopOnError: false,
      stopOnWarning: true
    },

    singleRun: true

  });
};

/**
  Loads configuration while ensuring sounce-map is enabled
 */
function loadWebpackConfig () {
  var webpackConfig = require('./webpack.config.js');
  webpackConfig.devtool = 'inline-source-map';
  webpackConfig.module.preLoaders = [
    {
      test: /\.jsx?$/,
      include: path.resolve('lib'),
      loader: 'isparta'
    }
  ];
  return webpackConfig;
}


const filterComponents = [
	'NUMBERBOX',
	'TAGCLOUD',
	'TOGGLEBUTTON',
	'DATEPICKER',
	'DATERANGE',
	'MULTIDATALIST',
	'MULTIDROPDOWNLIST',
	'MULTILIST',
	'SINGLEDATALIST',
	'SINGLEDROPDOWNLIST',
	'SINGLELIST',
	'DYNAMICRANGESLIDER',
	'MULTIDROPDOWNRANGE',
	'MULTIRANGE',
	'RANGESLIDER',
	'RATINGSFILTER',
	'SINGLEDROPDOWNRANGE',
	'SINGLERANGE',
];

// components storing range as array
const rangeComponents = [
	'DATERANGE',
	'DYNAMICRANGESLIDER',
	'RANGESLIDER',
	'RANGEINPUT',
	'RATINGSFILTER',
];

// components storing range as object
const rangeObjectComponents = [
	'SINGLERANGE',
	'SINGLEDROPDOWNRANGE',
	'MULTIRANGE',
	'MULTIDROPDOWNRANGE',
];

function parseRangeObject(filterKey, rangeObject) {
	return `${filterKey}=${rangeObject.start}~${rangeObject.end}`;
}

function parseFilterValue(componentId, componentValues) {
	const { label, value, componentType } = componentValues;
	const filterKey = label || componentId;
	if (rangeComponents.includes(componentType)) {
		// range components store values as an array to depict start and end range
		return `${filterKey}=${value[0]}~${value[1]}`;
	} else if (rangeObjectComponents.includes(componentType)) {
		// for range components with values in the form { start, end }
		if (Array.isArray(value)) {
			return value.map(item => parseRangeObject(filterKey, item))
				.join();
		}
		return parseRangeObject(filterKey, value);
	} else if (Array.isArray(value)) {
		// for components having values in the form { label, value }
		const isObject = typeof value[0] === 'object' && value[0] !== null;
		return isObject
			? value.map(item => `${filterKey}=${item.value}`).join()
			: value.map(item => `${filterKey}=${item}`).join();
	}
	return `${filterKey}=${value}`;
}

// transforms the selectedValues from store into the X-Search-Filters string for analytics
function getFilterString(selectedValues) {
	if (selectedValues && Object.keys(selectedValues).length) {
		return Object
			// take all selectedValues
			.entries(selectedValues)
			// filter out filter components having some value
			.filter(([, componentValues]) =>
				filterComponents.includes(componentValues.componentType)
					// in case of an array filter out empty array values as well
					&& (
						(componentValues.value && componentValues.value.length)
						// also consider range values in the shape { start, end }
						|| componentValues.value.start || componentValues.value.end
					))
			// parse each filter value
			.map(([componentId, componentValues]) => parseFilterValue(componentId, componentValues))
			// return as a string separated with comma
			.join();
	}
	return null;
}

export {
	filterComponents,
	rangeComponents,
	rangeObjectComponents,
	parseFilterValue,
	parseRangeObject,
};
export default getFilterString;