import { PickerValue } from '../../CCWheelPicker/utils'
import { PickerValueForDate } from './DateHelper'

export type FormatTypeForNumber = {
  label: string
  startOffset: number
  upperNumber: number
  requiredDigit: boolean
  numberOptions: true
}
export type FormatTypeForText = {
  label: string
  options: PickerValue[]
  numberOptions: false
}

export type FormatTypes = FormatTypeForNumber | FormatTypeForText

/**
 * フォーマットを分割する
 * 共通関数
 * @param format
 * @returns {string[]}
 */
export function getEachSlotFormat(format: string): { format: string; subscript: boolean }[] {
  const pattern = /\{(.*?)\}/g
  let match
  const targets: string[] = []

  while ((match = pattern.exec(format)) !== null) {
    targets.push(match[1])
  }
  const allTarget = format.split(pattern)

  const results = allTarget
    .map((e) => {
      if (targets.includes(e)) return { format: e, subscript: false }
      return { format: e, subscript: true }
    })
    .filter((e) => e.format !== '')

  return results
}

/**
 * 各スロットのOptionの作成
 * 共通で使用できる
 * @param val {string} フォーマット{}を含むテキストを吹き出した情報 ex: yyyy
 */
export function createEachOptions(val: string, dataFormats: FormatTypes[]) {
  const options = [] as PickerValueForDate[] | PickerValue[]

  const format = dataFormats.find((e) => val.includes(e.label))
  if (!!format) {
    if (format.numberOptions === false) {
      return format.options
    }
    for (let i = format.startOffset; i <= format.upperNumber; i++) {
      const label = format.requiredDigit === true && i < 10 ? `0${i}` : `${i}`
      options.push({
        label: val.replace(format.label, label),
        value: val.replace(format.label, label),
      })
    }

    return options
  }

  return options
}
