/**
Copyright: 2024 Contrast Security, Inc
  Contact: support@contrastsecurity.com
  License: Commercial

  NOTICE: This Software and the patented inventions embodied within may only be
  used as part of Contrast Security’s commercial offerings. Even though it is
  made available through public repositories, use of this Software is subject to
  the applicable End User Licensing Agreement found at
  https://www.contrastsecurity.com/enduser-terms-0317a or as otherwise agreed
  between Contrast Security and the End User. The Software may not be reverse
  engineered, modified, repackaged, sold, redistributed or otherwise used in a
  way not consistent with the End User License Agreement.
*/
'use strict';

const bigInt = require('big-integer');

// returns an array of '*' the same length as the input string
function createBits(str) {
  return str.split('').map(function() {
    return '*';
  });
}

function checkTagByName(tagRange, tags) {
  let i, tag;

  const subject = tagRange.tag;

  for (i = 0; i < tags.length; i++) {
    tag = tags[i];
    if (subject === tag) {
      return true;
    }
  }
}

function makeBitset({
  value,
  tagRanges,
  disallowedTags = [],
  requiredTags = ['untrusted']
}) {
  let bs = createBits(value);

  if (tagRanges && tagRanges.length > 0) {
    tagRanges.forEach(function(range) {
      if (checkTagByName(range, requiredTags)) {
        for (let i = range.start; i <= range.stop; i++) {
          if (bs[i] !== '0') {
            bs[i] = '1';
          }
        }
      } else if (checkTagByName(range, disallowedTags)) {
        for (let j = range.start; j <= range.stop; j++) {
          bs[j] = '0';
        }
      }
    });
  }

  // fill out the un-tagged portions with 0s
  bs = bs.map(function(bit) {
    if (bit === '*') return '0';
    return bit;
  });

  return bs.join('');
}

// convert binary sting to bigint and return string value of that number
function bin2dec(num) {
  return num
    .split('')
    .reverse()
    .reduce(function(x, y, i) {
      return y === '1' ? bigInt(x).plus(bigInt(2).pow(i)) : x;
    }, 0)
    .toString();
}

module.exports.bin2dec = bin2dec;
module.exports.createBits = createBits;
module.exports.makeBitset = makeBitset;
