import { ReposConfigurationWithDefaultsApplied } from './configTypes.ts'
import { Ref, FileInfo } from './dataTypes.ts'

export const colorAndPercentMap = async (
  reposConfig: ReposConfigurationWithDefaultsApplied,
  ref: Ref,
  files: (filename: string, sha: string) => Promise<FileInfo>,
) => {
  const languageCounts = new Map<string, number>()
  const countPromises = Array.from(ref.fileList.keys()).map(async (currentFile) => {
    return new Promise<void>(async (resolve) => {
      const fileParts = currentFile.split(".")
      const fileExtension = fileParts[fileParts.length - 1]
// todo: add more ignoreable extensions or specific files
// (like package-lock.json). Allow glob patterns?
      if (fileExtension === 'gitignore') {
        resolve()
      }

      const fileLineCount = (await files(currentFile, ref.sha)).contents.split('\n').length
      languageCounts.set(fileExtension, (languageCounts.get(fileExtension) + fileLineCount) || fileLineCount)
      resolve()
    })
  })

  await Promise.all(countPromises)

  let languagePercentages: Array<[string, number]> = []
  const total = Array.from(ref.fileList.keys()).length

  for (const entry of languageCounts) {
    languagePercentages.push([entry[0], entry[1] / total])
  }
  languagePercentages.sort((a, b) => {
    return b[1] - a[1]
  })

  // Show graph for the top 5 languages, unless there are fewer than 5 total
  const numOfTopLanguages = Math.min(5, languagePercentages.length)
  const topLanguagePercentages = languagePercentages.slice(0, numOfTopLanguages)
  const otherLanguagePercent = languagePercentages.slice(numOfTopLanguages).reduce((sum, current) => {
    return sum + current[1]
  }, 0)

  const largestPercent = Math.max(...topLanguagePercentages.map(tuple => tuple[1]), otherLanguagePercent)

  // TODO: make dark mode work here
  const colors = reposConfig.defaultTemplate.colors.languageGraph

  const colorAndPercentMap = {}

  topLanguagePercentages.forEach((percentTuple, index) => {
    const color = colors[index % (colors.length - 1)].light
    colorAndPercentMap[percentTuple[0]] = {
      color,
      percentOfTotal: percentTuple[1] / largestPercent
    }
  })

  if (otherLanguagePercent > 0) {
    colorAndPercentMap['other'] = {
      color: colors[colors.length - 1].light,
      percentOfTotal: otherLanguagePercent / largestPercent
    }
  }

  return colorAndPercentMap
}
