const assert = require('assert');
const clientPatcher = require('../clientPatcher');

function bytesAreZero(buffer) {
  for (const byte of buffer) {
    if (byte !== 0x00) {
      return false;
    }
  }
  return true;
}

const directStrategy = clientPatcher.getDomainStrategy('authws.net');
assert.strictEqual(directStrategy.mode, 'direct');
assert.strictEqual(directStrategy.mainDomain, 'authws.net');
assert.strictEqual(directStrategy.subdomainPrefix, '');

const splitStrategy = clientPatcher.getDomainStrategy('auth.sanasol.ws');
assert.strictEqual(splitStrategy.mode, 'split');
assert.strictEqual(splitStrategy.subdomainPrefix, 'auth.s');
assert.strictEqual(splitStrategy.mainDomain, 'anasol.ws');

const oldSubdomain = clientPatcher.stringToLengthPrefixed('https://tools.');
const newSubdomain = clientPatcher.stringToLengthPrefixed('https://');
const replaceResult = clientPatcher.replaceBytes(oldSubdomain, oldSubdomain, newSubdomain);
const padding = replaceResult.buffer.slice(newSubdomain.length, oldSubdomain.length);
assert.ok(bytesAreZero(padding), 'Expected null padding after shorter replacement');

const oldDomainUtf16 = clientPatcher.stringToUtf16LE('hytale.com');
const smartResult = clientPatcher.findAndReplaceDomainSmart(oldDomainUtf16, 'hytale.com', 'auth.ws');
const newDomainUtf16 = clientPatcher.stringToUtf16LE('auth.ws');
assert.ok(smartResult.buffer.slice(0, newDomainUtf16.length).equals(newDomainUtf16));
const smartPadding = smartResult.buffer.slice(newDomainUtf16.length, oldDomainUtf16.length);
assert.ok(bytesAreZero(smartPadding), 'Expected null padding in smart replacement');

console.log('clientPatcher tests passed');
