/**
 * Testing framework with support for generating tests.
 *
 * ```js
 * // test.js template for creating a test executable
 * import { runTests } from 'lib0/testing'
 * import * as log from 'lib0/logging'
 * import * as mod1 from './mod1.test.js'
 * import * as mod2 from './mod2.test.js'

 * import { isBrowser, isNode } from 'lib0/environment.js'
 *
 * if (isBrowser) {
 *   // optional: if this is ran in the browser, attach a virtual console to the dom
 *   log.createVConsole(document.body)
 * }
 *
 * runTests({
 *  mod1,
 *  mod2,
 * }).then(success => {
 *   if (isNode) {
 *     process.exit(success ? 0 : 1)
 *   }
 * })
 * ```
 *
 * ```js
 * // mod1.test.js
 * /**
 *  * runTests automatically tests all exported functions that start with "test".
 *  * The name of the function should be in camelCase and is used for the logging output.
 *  *
 *  * @ param {t.TestCase} tc
 *  *\/
 * export const testMyFirstTest = tc => {
 *   t.compare({ a: 4 }, { a: 4 }, 'objects are equal')
 * }
 * ```
 *
 * Now you can simply run `node test.js` to run your test or run test.js in the browser.
 *
 * @module testing
 */

import * as log from 'lib0/logging'
import { simpleDiffString } from './diff.js'
import * as object from './object.js'
import * as string from './string.js'
import * as math from './math.js'
import * as random from './random.js'
import * as prng from './prng.js'
import * as statistics from './statistics.js'
import * as array from './array.js'
import * as env from './environment.js'
import * as json from './json.js'
import * as time from './time.js'
import * as promise from './promise.js'
import * as performance from 'lib0/performance'
import * as equalityTrait from './trait/equality.js'

export { production } from './environment.js'
export const extensive = env.hasConf('extensive')

/* c8 ignore next */
export const envSeed = env.hasParam('--seed') ? Number.parseInt(env.getParam('--seed', '0')) : null

export class TestCase {
  /**
   * @param {string} moduleName
   * @param {string} testName
   */
  constructor (moduleName, testName) {
    /**
     * @type {string}
     */
    this.moduleName = moduleName
    /**
     * @type {string}
     */
    this.testName = testName
    /**
     * This type can store custom information related to the TestCase
     *
     * @type {Map<string,any>}
     */
    this.meta = new Map()
    this._seed = null
    this._prng = null
  }

  resetSeed () {
    this._seed = null
    this._prng = null
  }

  /**
   * @type {number}
   */
  /* c8 ignore next */
  get seed () {
    /* c8 ignore else */
    if (this._seed === null) {
      /* c8 ignore next */
      this._seed = envSeed === null ? random.uint32() : envSeed
    }
    return this._seed
  }

  /**
   * A PRNG for this test case. Use only this PRNG for randomness to make the test case reproducible.
   *
   * @type {prng.PRNG}
   */
  get prng () {
    /* c8 ignore else */
    if (this._prng === null) {
      this._prng = prng.create(this.seed)
    }
    return this._prng
  }
}

export const repetitionTime = Number(env.getParam('--repetition-time', '50'))
/* c8 ignore next */
const testFilter = env.hasParam('--filter') ? env.getParam('--filter', '') : null

/* c8 ignore next */
const testFilterRegExp = testFilter !== null ? new RegExp(testFilter) : /.*/

const repeatTestRegex = /^(repeat|repeating)\s/

/**
 * @param {string} moduleName
 * @param {string} name
 * @param {function(TestCase):void|Promise<any>} f
 * @param {number} i
 * @param {number} numberOfTests
 */
export const run = async (moduleName, name, f, i, numberOfTests) => {
  const uncamelized = string.fromCamelCase(name.slice(4), ' ')
  const filtered = !testFilterRegExp.test(`[${i + 1}/${numberOfTests}] ${moduleName}: ${uncamelized}`)
  /* c8 ignore next 3 */
  if (filtered) {
    return true
  }
  const tc = new TestCase(moduleName, name)
  const repeat = repeatTestRegex.test(uncamelized)
  const groupArgs = [log.GREY, `[${i + 1}/${numberOfTests}] `, log.PURPLE, `${moduleName}: `, log.BLUE, uncamelized]
  /* c8 ignore next 5 */
  if (testFilter === null) {
    log.groupCollapsed(...groupArgs)
  } else {
    log.group(...groupArgs)
  }
  const times = []
  const start = performance.now()
  let lastTime = start
  /**
   * @type {any}
   */
  let err = null
  performance.mark(`${name}-start`)
  do {
    try {
      const p = f(tc)
      if (promise.isPromise(p)) {
        await p
      }
    } catch (_err) {
      err = _err
    }
    const currTime = performance.now()
    times.push(currTime - lastTime)
    lastTime = currTime
    if (repeat && err === null && (lastTime - start) < repetitionTime) {
      tc.resetSeed()
    } else {
      break
    }
  } while (err === null && (lastTime - start) < repetitionTime)
  performance.mark(`${name}-end`)
  /* c8 ignore next 3 */
  if (err !== null && err.constructor !== SkipError) {
    log.printError(err)
  }
  performance.measure(name, `${name}-start`, `${name}-end`)
  log.groupEnd()
  const duration = lastTime - start
  let success = true
  times.sort((a, b) => a - b)
  /* c8 ignore next 3 */
  const againMessage = env.isBrowser
    ? `     - ${window.location.host + window.location.pathname}?filter=\\[${i + 1}/${tc._seed === null ? '' : `&seed=${tc._seed}`}`
    : `\nrepeat: npm run test -- --filter "\\[${i + 1}/" ${tc._seed === null ? '' : `--seed ${tc._seed}`}`
  const timeInfo = (repeat && err === null)
    ? ` - ${times.length} repetitions in ${time.humanizeDuration(duration)} (best: ${time.humanizeDuration(times[0])}, worst: ${time.humanizeDuration(array.last(times))}, median: ${time.humanizeDuration(statistics.median(times))}, average: ${time.humanizeDuration(statistics.average(times))})`
    : ` in ${time.humanizeDuration(duration)}`
  if (err !== null) {
    /* c8 ignore start */
    if (err.constructor === SkipError) {
      log.print(log.GREY, log.BOLD, 'Skipped: ', log.UNBOLD, uncamelized)
    } else {
      success = false
      log.print(log.RED, log.BOLD, 'Failure: ', log.UNBOLD, log.UNCOLOR, uncamelized, log.GREY, timeInfo, againMessage)
    }
    /* c8 ignore stop */
  } else {
    log.print(log.GREEN, log.BOLD, 'Success: ', log.UNBOLD, log.UNCOLOR, uncamelized, log.GREY, timeInfo, againMessage)
  }
  return success
}

/**
 * Describe what you are currently testing. The message will be logged.
 *
 * ```js
 * export const testMyFirstTest = tc => {
 *   t.describe('crunching numbers', 'already crunched 4 numbers!') // the optional second argument can describe the state.
 * }
 * ```
 *
 * @param {string} description
 * @param {string} info
 */
export const describe = (description, info = '') => log.print(log.BLUE, description, ' ', log.GREY, info)

/**
 * Describe the state of the current computation.
 * ```js
 * export const testMyFirstTest = tc => {
 *   t.info(already crunched 4 numbers!') // the optional second argument can describe the state.
 * }
 * ```
 *
 * @param {string} info
 */
export const info = info => describe('', info)

export const printDom = log.printDom

export const printCanvas = log.printCanvas

/**
 * Group outputs in a collapsible category.
 *
 * ```js
 * export const testMyFirstTest = tc => {
 *   t.group('subtest 1', () => {
 *     t.describe('this message is part of a collapsible section')
 *   })
 *   await t.groupAsync('subtest async 2', async () => {
 *     await someaction()
 *     t.describe('this message is part of a collapsible section')
 *   })
 * }
 * ```
 *
 * @param {string} description
 * @param {function(...any):void} f
 */
export const group = (description, f) => {
  log.group(log.BLUE, description)
  try {
    f()
  } finally {
    log.groupEnd()
  }
}

/**
 * Group outputs in a collapsible category.
 *
 * ```js
 * export const testMyFirstTest = async tc => {
 *   t.group('subtest 1', () => {
 *     t.describe('this message is part of a collapsible section')
 *   })
 *   await t.groupAsync('subtest async 2', async () => {
 *     await someaction()
 *     t.describe('this message is part of a collapsible section')
 *   })
 * }
 * ```
 *
 * @param {string} description
 * @param {function(...any):Promise<any>} f
 */
export const groupAsync = async (description, f) => {
  log.group(log.BLUE, description)
  try {
    await f()
  } finally {
    log.groupEnd()
  }
}

/**
 * Measure the time that it takes to calculate something.
 *
 * ```js
 * export const testMyFirstTest = async tc => {
 *   t.measureTime('measurement', () => {
 *     heavyCalculation()
 *   })
 *   await t.groupAsync('async measurement', async () => {
 *     await heavyAsyncCalculation()
 *   })
 * }
 * ```
 *
 * @param {string} message
 * @param {function(...any):void} f
 * @return {number} Returns a promise that resolves the measured duration to apply f
 */
export const measureTime = (message, f) => {
  let duration
  const start = performance.now()
  try {
    f()
  } finally {
    duration = performance.now() - start
    log.print(log.PURPLE, message, log.GREY, ` ${time.humanizeDuration(duration)}`)
  }
  return duration
}

/**
 * Measure the time that it takes to calculate something.
 *
 * ```js
 * export const testMyFirstTest = async tc => {
 *   t.measureTimeAsync('measurement', async () => {
 *     await heavyCalculation()
 *   })
 *   await t.groupAsync('async measurement', async () => {
 *     await heavyAsyncCalculation()
 *   })
 * }
 * ```
 *
 * @param {string} message
 * @param {function(...any):Promise<any>} f
 * @return {Promise<number>} Returns a promise that resolves the measured duration to apply f
 */
export const measureTimeAsync = async (message, f) => {
  let duration
  const start = performance.now()
  try {
    await f()
  } finally {
    duration = performance.now() - start
    log.print(log.PURPLE, message, log.GREY, ` ${time.humanizeDuration(duration)}`)
  }
  return duration
}

/**
 * @template T
 * @param {Array<T>} as
 * @param {Array<T>} bs
 * @param {string} [m]
 * @return {boolean}
 */
export const compareArrays = (as, bs, m = 'Arrays match') => {
  if (as.length !== bs.length) {
    fail(m)
  }
  for (let i = 0; i < as.length; i++) {
    if (as[i] !== bs[i]) {
      fail(m)
    }
  }
  return true
}

/**
 * @param {string} a
 * @param {string} b
 * @param {string} [m]
 * @throws {TestError} Throws if tests fails
 */
export const compareStrings = (a, b, m = 'Strings match') => {
  if (a !== b) {
    const diff = simpleDiffString(a, b)
    log.print(log.GREY, a.slice(0, diff.index), log.RED, a.slice(diff.index, diff.remove), log.GREEN, diff.insert, log.GREY, a.slice(diff.index + diff.remove))
    fail(m)
  }
}

/**
 * @template K,V
 * @param {Object<K,V>} a
 * @param {Object<K,V>} b
 * @param {string} [m]
 * @throws {TestError} Throws if test fails
 */
export const compareObjects = (a, b, m = 'Objects match') => { object.equalFlat(a, b) || fail(m) }

/**
 * @param {any} _constructor
 * @param {any} a
 * @param {any} b
 * @param {string} path
 * @throws {TestError}
 */
const compareValues = (_constructor, a, b, path) => {
  if (a !== b) {
    fail(`Values ${json.stringify(a)} and ${json.stringify(b)} don't match (${path})`)
  }
  return true
}

/**
 * @param {string?} message
 * @param {string} reason
 * @param {string} path
 * @throws {TestError}
 */
const _failMessage = (message, reason, path) => fail(
  message === null
    ? `${reason} ${path}`
    : `${message} (${reason}) ${path}`
)

/**
 * @param {any} a
 * @param {any} b
 * @param {string} path
 * @param {string?} message
 * @param {function(any,any,any,string,any):boolean} customCompare
 */
const _compare = (a, b, path, message, customCompare) => {
  // we don't use assert here because we want to test all branches (istanbul errors if one branch is not tested)
  if (a == null || b == null) {
    return compareValues(null, a, b, path)
  }
  if (a[equalityTrait.EqualityTraitSymbol] != null) {
    if (a[equalityTrait.EqualityTraitSymbol](b)) {
      return true
    } else {
      _failMessage(message, 'Not equal by equality trait', path)
    }
  }
  if (a.constructor !== b.constructor) {
    _failMessage(message, 'Constructors don\'t match', path)
  }
  let success = true
  switch (a.constructor) {
    case ArrayBuffer:
      a = new Uint8Array(a)
      b = new Uint8Array(b)
    // eslint-disable-next-line no-fallthrough
    case Uint8Array: {
      if (a.byteLength !== b.byteLength) {
        _failMessage(message, 'ArrayBuffer lengths match', path)
      }
      for (let i = 0; success && i < a.length; i++) {
        success = success && a[i] === b[i]
      }
      break
    }
    case Set: {
      if (a.size !== b.size) {
        _failMessage(message, 'Sets have different number of attributes', path)
      }
      // @ts-ignore
      a.forEach(value => {
        if (!b.has(value)) {
          _failMessage(message, `b.${path} does have ${value}`, path)
        }
      })
      break
    }
    case Map: {
      if (a.size !== b.size) {
        _failMessage(message, 'Maps have different number of attributes', path)
      }
      // @ts-ignore
      a.forEach((value, key) => {
        if (!b.has(key)) {
          _failMessage(message, `Property ${path}["${key}"] does not exist on second argument`, path)
        }
        _compare(value, b.get(key), `${path}["${key}"]`, message, customCompare)
      })
      break
    }
    case undefined: // undefined is often set as a constructor for objects
    case Object:
      if (object.length(a) !== object.length(b)) {
        _failMessage(message, 'Objects have a different number of attributes', path)
      }
      object.forEach(a, (value, key) => {
        if (!object.hasProperty(b, key)) {
          _failMessage(message, `Property ${path} does not exist on second argument`, path)
        }
        _compare(value, b[key], `${path}["${key}"]`, message, customCompare)
      })
      break
    case Array:
      if (a.length !== b.length) {
        _failMessage(message, 'Arrays have a different number of attributes', path)
      }
      // @ts-ignore
      a.forEach((value, i) => _compare(value, b[i], `${path}[${i}]`, message, customCompare))
      break
    /* c8 ignore next 4 */
    default:
      if (!customCompare(a.constructor, a, b, path, compareValues)) {
        _failMessage(message, `Values ${json.stringify(a)} and ${json.stringify(b)} don't match`, path)
      }
  }
  assert(success, message)
  return true
}

/**
 * @template T
 * @param {T} a
 * @param {T} b
 * @param {string?} [message]
 * @param {function(any,T,T,string,any):boolean} [customCompare]
 */
export const compare = (a, b, message = null, customCompare = compareValues) => _compare(a, b, 'obj', message, customCompare)

/**
 * @template T
 * @param {T} property
 * @param {string?} [message]
 * @return {asserts property is NonNullable<T>}
 * @throws {TestError}
 */
/* c8 ignore next */
export const assert = (property, message = null) => { property || fail(`Assertion failed${message !== null ? `: ${message}` : ''}`) }

/**
 * @param {function(...any):Promise<any>} f
 */
export const promiseRejected = async f => {
  try {
    await f()
  } catch (err) {
    return
  }
  fail('Expected promise to fail')
}

/**
 * @param {function(...any):void} f
 * @throws {TestError}
 */
export const fails = f => {
  try {
    f()
  } catch (_err) {
    log.print(log.GREEN, '⇖ This Error was expected')
    return
  }
  fail('Expected this to fail')
}

/**
 * @param {function(...any):Promise<any>} f
 * @throws {TestError}
 */
export const failsAsync = async f => {
  try {
    await f()
  } catch (_err) {
    log.print(log.GREEN, '⇖ This Error was expected')
    return
  }
  fail('Expected this to fail')
}

/**
 * @param {Object<string, Object<string, function(TestCase):void|Promise<any>>>} tests
 */
export const runTests = async tests => {
  /**
   * @param {string} testname
   */
  const filterTest = testname => testname.startsWith('test') || testname.startsWith('benchmark')
  const numberOfTests = object.map(tests, mod => object.map(mod, (f, fname) => /* c8 ignore next */ f && filterTest(fname) ? 1 : 0).reduce(math.add, 0)).reduce(math.add, 0)
  let successfulTests = 0
  let testnumber = 0
  const start = performance.now()
  for (const modName in tests) {
    const mod = tests[modName]
    for (const fname in mod) {
      const f = mod[fname]
      /* c8 ignore else */
      if (f && filterTest(fname)) {
        const repeatEachTest = 1
        let success = true
        for (let i = 0; success && i < repeatEachTest; i++) {
          success = await run(modName, fname, f, testnumber, numberOfTests)
        }
        testnumber++
        /* c8 ignore else */
        if (success) {
          successfulTests++
        }
      }
    }
  }
  const end = performance.now()
  log.print('')
  const success = successfulTests === numberOfTests
  /* c8 ignore start */
  if (success) {
    log.print(log.GREEN, log.BOLD, 'All tests successful!', log.GREY, log.UNBOLD, ` in ${time.humanizeDuration(end - start)}`)
    log.printImgBase64(nyanCatImage, 50)
  } else {
    const failedTests = numberOfTests - successfulTests
    log.print(log.RED, log.BOLD, `> ${failedTests} test${failedTests > 1 ? 's' : ''} failed`)
  }
  /* c8 ignore stop */
  return success
}

class TestError extends Error {}

/**
 * @param {string} reason
 * @throws {TestError}
 */
export const fail = reason => {
  log.print(log.RED, log.BOLD, 'X ', log.UNBOLD, reason)
  throw new TestError('Test Failed')
}

class SkipError extends Error {}

/**
 * @param {boolean} cond If true, this tests will be skipped
 * @throws {SkipError}
 */
export const skip = (cond = true) => {
  if (cond) {
    throw new SkipError('skipping..')
  }
}

// eslint-disable-next-line
const nyanCatImage = ' '
