const chunkify = require('./chunkify')

const STATUSES = {
  WIP: 'WIP',
  SUCCESS: 'SUCCESS',
  SUCCESS_CHUNKED: 'SUCCESS_CHUNKED',
  ERROR: 'ERROR',
}
const _DEFAULT_CHUNK_BYTE_LENGTH = 268435456 // 256MB

function createPollResponse(state, {chunkByteLength = 0} = {}) {
  if (!state) {
    return {
      status: STATUSES.ERROR,
      error: 'unexpected poll request received - cannot find state of current operation',
    }
  } else if (state.value) {
    if (chunkByteLength) {
      if (!state.chunks) {
        try {
          const stringified = JSON.stringify(state.value)
          state.chunks = chunkify(stringified, chunkByteLength)
          if (state.chunks.length > 0) {
            state.from = 0
            state.value = stringified
          }
        } catch (e) {
          return {status: STATUSES.ERROR, error: e.message}
        }
      }
      if (state.from >= 0) {
        return {
          status: STATUSES.SUCCESS_CHUNKED,
          value: state.value.substring(state.from, (state.from = state.chunks.shift())),
          done: !state.from,
        }
      }
    }
    return {status: STATUSES.SUCCESS, value: state.value}
  } else if (state.error) {
    return {status: STATUSES.ERROR, error: state.error}
  } else {
    return {status: STATUSES.WIP}
  }
}

function poll(context, key, options = {}) {
  context = context || {}
  const result = createPollResponse(context[key], options)

  if (
    result.status === STATUSES.SUCCESS ||
    result.status === STATUSES.ERROR ||
    (result.status === STATUSES.SUCCESS_CHUNKED && result.done)
  ) {
    context[key] = null
  }

  return result
}

module.exports = poll
