
import { access } from '@things-factory/utils'

export function checkValidPose(name, position) {
  var sum = 0
  for (var idx in position) {
    sum += position[idx]
  }
  if (isNaN(sum)) {
    throw new Error(`correct value position is not given for ${name} : ${position}`)
  }
}

export function getPositionFromAccessor(name, accessor, data, logger) {
  var position = accessor ? access(accessor, data) : {}
  logger.info(`${name}: ${accessor}, result: ${position}`)

  if (!position || typeof position !== 'object') {
    throw new Error(`correct type position is not given : ${position}`)
  }

  if (position instanceof Array) {
    position = {
      x: Number(position[0]),
      y: Number(position[1]),
      z: Number(position[2]),
      u: Number(position[3]),
      v: Number(position[4]),
      w: Number(position[5])
    }
  }

  return position
}

export function prunePose(name, position, logger) {
  var pruned = {
    ...position
  }

  for (let k in pruned) {
    let v = pruned[k]

    if (isNaN(v) || v === null || v === '') {
      delete pruned[k]
    } else {
      pruned[k] = Number(pruned[k])
    }
  }

  return pruned
}

export function arrangeOffset(offsetPose, logger) {
  var offsetResult = {
    ...offsetPose
  }

  console.log('offsetResult: ', offsetResult)

  for (let k in offsetPose) {
    let v = offsetResult[k]

    if (isNaN(v) || v === null || v === '') {
      offsetResult[k] = 0
    }
    else {
      offsetResult[k] = Number(offsetResult[k])
    }
  }

  return offsetResult
}
