/* eslint no-console: 0 */
/* eslint no-undef: 0 */
const CHARSET = '123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

const string2BigInt = str => {
  const len = str.length
  let tmp = ''

  for (let i = 0; i < len; i += 2) {
    tmp = str.substring(i, i + 2) + tmp
  }
  // console.log(tmp, 'tmp')

  return BigInt('0x' + tmp)
}

const encodeLong = number => { // bigInt number
  if (number <= 0) return '0'

  let buf = ''
  const charLength = BigInt(CHARSET.length)
  while (number != 0) {
    buf = CHARSET[number % charLength] + buf
    number /= charLength
  }

  return buf
}

const fileMd5ToName = md5 => {
  if (md5 === undefined || typeof md5 !== 'string' || md5.length % 2 !== 0) {
    console.error('md5 must be string and its size must be an even number')
    return
  }
  const md5Length = md5.length
  const firstHalf = string2BigInt(md5.substring(0, md5Length / 2))
  const lastHalf = string2BigInt(md5.substring(md5Length / 2, md5Length))

  return `${encodeLong(firstHalf)}0${encodeLong(lastHalf)}`
}

export {
  encodeLong,
  fileMd5ToName
}
