import type { ParsedChart } from '../../game/sscParser'

export const AUDIO_EXTS = ['.ogg', '.mp3', '.wav']
export const CHART_EXTS = ['.ssc', '.sm']
export const IMAGE_EXTS = ['.png', '.jpg', '.jpeg', '.gif', '.bmp']

export function ext(name: string): string {
  const i = name.lastIndexOf('.')
  return i >= 0 ? name.slice(i).toLowerCase() : ''
}

export function basename(path: string): string {
  const parts = path.split('/')
  return parts[parts.length - 1]
}

export function generateId(): string {
  return `custom-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
}

export function estimateDuration(chart: ParsedChart): string {
  let maxTime = 0
  for (const d of chart.difficulties) {
    for (const n of d.notes) {
      if (n.time > maxTime) maxTime = n.time
    }
  }
  const mins = Math.floor(maxTime / 60)
  const secs = Math.floor(maxTime % 60)
  return `${mins}:${secs.toString().padStart(2, '0')}`
}

export function easiestDifficulty(chart: ParsedChart): string {
  if (chart.difficulties.length === 0) return ''
  const beginner = chart.difficulties.find((d) => d.difficulty === 'Beginner')
  if (beginner) return beginner.difficulty
  return chart.difficulties.reduce((a, b) => (a.meter < b.meter ? a : b)).difficulty
}

export function placeholderImageFile(): File {
  const canvas = document.createElement('canvas')
  canvas.width = 1
  canvas.height = 1
  const ctx = canvas.getContext('2d')
  if (!ctx) {
    return new File([], 'placeholder.png', { type: 'image/png' })
  }
  ctx.fillStyle = 'rgba(0,0,0,0)'
  ctx.fillRect(0, 0, 1, 1)
  const dataUrl = canvas.toDataURL('image/png')
  const binary = atob(dataUrl.split(',')[1])
  const bytes = new Uint8Array(binary.length)
  for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)
  return new File([bytes], 'placeholder.png', { type: 'image/png' })
}
