import { Timestamp } from '@firebase/firestore'
import { copy } from 'copy-anything'

/**
 * 時間を文字に変換
 * @param payload Date | Timestamp | string | null
 * @param string 202301 | 20230101 | 2023/01/01 | 2023/01/01 00:00:00
 * @param format YYYY/MM/DD hh:mm:ss
 */
export const dateFormat = (payload: Date | Timestamp | string | null, format: string) => {
  let date = copy(payload)
  if (!date) return ''
  if (typeof date === 'string') {
    if (/^(\d{6})$/.test(date)) {
      date = date.replace(/^(\d{4})(\d{2}).*$/, '$1-$2-01')
    }
    if (/^(\d{8})$/.test(date)) {
      date = date.replace(/^(\d{4})(\d{2})(\d{2}).*$/, '$1-$2-$3')
    }
    if (!/^(\d{4}).([0-1]\d).([0-3]\d).*$/.test(date)) return 'error'
    const strYear = Number(date.slice(0, 4))
    const strMonth = Number(date.slice(5, 7)) - 1
    const strDate = Number(date.slice(8, 10))
    date = new Date(strYear, strMonth, strDate)
  }
  if (date instanceof Timestamp) {
    date = date.toDate()
  }

  format = format.replace(/YYYY/g, date.getFullYear().toString())
  format = format.replace(/MM/g, ('0' + (date.getMonth() + 1)).slice(-2))
  format = format.replace(/DD/g, ('0' + date.getDate()).slice(-2))
  format = format.replace(/hh/g, ('0' + date.getHours()).slice(-2))
  format = format.replace(/mm/g, ('0' + date.getMinutes()).slice(-2))
  format = format.replace(/ss/g, ('0' + date.getSeconds()).slice(-2))
  format = format.replace(/SSS/g, ('00' + date.getMilliseconds()).slice(-3))
  return format
}

export const isDateFormatEnable = (date: Date | Timestamp | string | null) => {
  if (dateFormat(date, 'YYYY-MM-DD') === 'error') return false
  if (dateFormat(date, 'YYYY-MM-DD') === '') return false
  return true
}
