import { createRequire } from 'module';
const require = createRequire(import.meta.url);

global.window = {}
global.requestAnimationFrame = function() {}
global._ = require('lodash')

const YAML = require('js-yaml')
const fs = require('fs')
const path = require('path')

function _getCallerFile() {
  var originalFunc = Error.prepareStackTrace

  var callerfile
  try {
    var error = new Error()
    var currentfile

    Error.prepareStackTrace = function(error, stack) {
      return stack
    }

    currentfile = error.stack.shift().getFileName()

    while (error.stack.length) {
      callerfile = error.stack.shift().getFileName()

      if (currentfile !== callerfile) break
    }
  } catch (e) {
    // do nothing
  }

  Error.prepareStackTrace = originalFunc

  return callerfile
}

global.requireYAML = function(file_path) {
  const dirname = path.dirname(_getCallerFile()).slice('file://'.length)

  const yaml = fs.readFileSync(path.resolve(dirname, file_path))
  const json = YAML.load(yaml.toString())
  convertUndefinedStringToUndefined(json)


  return json
}

function convertUndefinedStringToUndefined(json) {
  if (typeof json == 'object' || Array.isArray(json)) {
    for (var i in json) {
      _convertUndefinedStringToUndefined(json, i, json[i])
    }
  }
}

function _convertUndefinedStringToUndefined(parent, key, child) {
  if (typeof child == 'object' || Array.isArray(child)) {
    for (var i in child) {
      _convertUndefinedStringToUndefined(child, i, child[i])
    }
  } else if (child == 'undefined') {
    parent[key] = undefined
  }
}

global.parseDatastoreMethod = function(datastore, method, args, { subscriber = {}, callback = () => {} }= {}) {
  switch (method) {
    case 'subscribe':
      if (args.length == 4) {
        datastore.subscribe(args[0], subscriber, callback, args.slice(-1)[0])
      } else {
        datastore.subscribe(args[0], subscriber, callback)
      }
      return
    case 'unsubscribe':
      if (args.length == 3) {
        datastore.unsubscribe(args[0], subscriber, callback)
      } else {
        datastore.unsubscribe(args[0], subscriber, callback, args.slice(-1)[0])
      }
    default:
      datastore[method](...args)
      return
  }
}