type TranslateFunction = (key: string) => string

const fileSize = (value: number, t: TranslateFunction): string => {
  if (value === 0) return '0 ' + t('B')
  
  const units = ['B', 'kB', 'MB', 'GB', 'TB'] as const
  const i = Math.floor(Math.log(value) / Math.log(1024))
  
  const index = Math.max(0, Math.min(i, units.length - 1))
  
  const result = (value / Math.pow(1024, index)).toFixed(1)
  
  const unitKey = units[index]
  
  return `${result} ${t(unitKey!)}`
}
 
interface ParsedFile {
  name: string
  ext: string
}

function parseFileName (filename: string): ParsedFile {
  const lastDotIndex = filename.lastIndexOf('.')
  
  if (lastDotIndex === -1) return { name: filename, ext: '' }
  
  return {
    name: filename.slice(0, lastDotIndex),
    ext: filename.slice(lastDotIndex + 1).toLowerCase()
  }
}

interface FileIcon {
  type: string
  icon: string
  color: string
}

function fileIcon (filename: string): FileIcon {
  const ext = parseFileName(filename).ext

  switch (ext) {
    case 'doc':
    case 'docx':
      return { type: 'doc', icon: 'pn-icon-file-doc', color: '#2B579A' }

    case 'xls':
    case 'xlsx':
    case 'csv':
      return { type: 'xls', icon: 'pn-icon-file-xls', color: '#217346' }

    case 'vsd':
    case 'vsdx':
      return { type: 'vsd', icon: 'pn-icon-file-vsd', color: '#3955A3' }

    case 'ppt':
    case 'pptx':
      return { type: 'ppt', icon: 'pn-icon-file-ppt', color: '#D24726' }

    case 'pdf':
      return { type: 'pdf', icon: 'pn-icon-file-pdf', color: '#D0021B' }

    case 'png':
    case 'jpg':
    case 'jpeg':
    case 'gif':
    case 'bmp':
    case 'webp':
    case 'svg':
      return { type: 'img', icon: 'pn-icon-file-img', color: '#4CAF50' }

    case 'mp3':
    case 'wav':
    case 'ogg':
      return { type: 'music', icon: 'pn-icon-file-audio', color: '#FF9800' }

    case 'mp4':
    case 'avi':
    case 'mov':
    case 'mkv':
      return { type: 'video', icon: 'pn-icon-file-video', color: '#9C27B0' }

    case 'js':
    case 'ts':
    case 'html':
    case 'css':
    case 'json':
    case 'xml':
      return { type: 'code', icon: 'pn-icon-file-code', color: '#999' }

    case 'txt':
      return { type: 'txt', icon: 'pn-icon-file-txt', color: '#757575' }

    case 'zip':
    case 'rar':
    case '7z':
    case 'tar':
    case 'gz':
      return { type: 'archive', icon: 'pn-icon-file-archive', color: '#F78E1E' }

    case 'skp':
      return { type: 'skp', icon: 'pn-icon-file-skp', color: '#CC0000' }

    case 'dwg':
    case 'dxf':
      return { type: 'cad', icon: 'pn-icon-file-dwg', color: '#00579D' }

    case 'ttf':
      return { type: 'font', icon: 'pn-icon-file-ttf', color: '#607D8B' }

    default:
      return { type: 'common', icon: 'pn-icon-file-default', color: '#9E9E9E' }
  }
}

export {
  fileSize,
  parseFileName,
  fileIcon
}
