import { useTunnelStoreWithOut } from '@/store/modules/tunnel'
import { sleep } from './index'
import tunnelConfigs from '@/config/tunnel'

const tunnelStore = useTunnelStoreWithOut()

export function numToStone (num: string | number) {

  const _num = +num || 0
  const left = +num % 1000

  const k = (_num - left) / 1000
  const after = (e) => {
    if (e < 10) return '00' + e
    if (e < 100) return '0' + e
    return e
  }

  return `K${k}+${after(left)}`

}

export function numToSection (num: number, direction: number) {

  const nowTunnel = [tunnelStore.getUpTunnel, tunnelStore.getDownTunnel][direction]

  if (!nowTunnel || !nowTunnel.long) return 0

  const { start, end, long } = nowTunnel

  if (num < start || num > end) return 0

  const distance = direction ? end - num : num - start

  const left = distance % tunnelConfigs.perSection
  const x = (distance - left) / tunnelConfigs.perSection + (left > 0 ? 1 : 0)

  return x

}

export async function awaitGet (call, count = 0) {

  const tm = 500
  const max = 12

  const val = call()

  if (val === null || typeof val === 'undefined' || val === '') {
    if (count <= max) {
      await sleep(tm)
      return await awaitGet(call, count + 1)
    } else {
      return false
    }
  } else {
    return true
  }

}