import { isSpecialMissing } from '@sasjs/utils/input/validators'

/**
 * Custom validator for numeric field that contains speical missings
 */
export function specialMissingNumericValidator(
  value: any,
  callback?: (valid: boolean) => void
) {
  if (value === undefined || value === null) {
    if (callback) callback(true)
    return true
  }

  if (!isNaN(value) && isFinite(value)) {
    if (callback) callback(true)
    return true
  }

  const valid = isSpecialMissing(value)

  if (callback) callback(valid)
  return valid
}

const DATETIME_REGEX = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/

/**
 * Validator for the custom `intl-datetime` cell type. Expects SAS' ISO datetime
 * form `YYYY-MM-DD HH:mm:ss`. Mirrors HOT's intl validators by honouring
 * `this.allowEmpty` for blank values. Bound by HOT to the cell properties, so
 * `this` carries `allowEmpty`.
 */
export function datetimeValidator(
  this: { allowEmpty?: boolean } | void,
  value: any,
  callback: (valid: boolean) => void
) {
  const allowEmpty = (this as { allowEmpty?: boolean })?.allowEmpty ?? true

  if (value === undefined || value === null || value === '') {
    callback(allowEmpty)
    return
  }

  callback(typeof value === 'string' && DATETIME_REGEX.test(value))
}
