import { type Repository } from '../src/dataTypes.ts'
import { NavHelper } from './helpers/nav.ts'

export default async (eleventyConfig: any, data: any, nav: ReturnType<typeof NavHelper>) => {
  const repo: Repository = data.currentRepo
  const branch: Repository['branches'][0] = data.currentBranch
  const renderContentIfAvailable = eleventyConfig.getFilter("renderContentIfAvailable")
  const getReadMe = eleventyConfig.getFilter("getReadMe")
  const latestCommit = repo.commits.get(branch.head)
  const latestCommitMessage = latestCommit.message.length > 72
    ? latestCommit.message.split('\n')[0].substr(0, 72) + '...'
    : latestCommit.message

  const languageCounts = branch.fileList.reduce((counts, currentFile) => {
    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') {
      return counts
    }

    counts.set(fileExtension, (counts.get(fileExtension) + 1) || 1)
    return counts
  }, new Map<string, number>())

  // todo: this is probably broken for repos that use fewer than 6 languages
  let languagePercentages: Array<[string, number]> = []
  const total = branch.fileList.length

  for (const entry of languageCounts) {
    languagePercentages.push([entry[0], entry[1] / total])
  }
  languagePercentages.sort((a, b) => {
    return b[1] - a[1]
  })
  const topLanguagePercentages = languagePercentages.slice(0, 5)
  const otherLanguagePercent = languagePercentages.slice(6, languagePercentages.length - 6).reduce((sum, current) => {
    return sum + current[1]
  }, 0)

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

  return `
    <div class="row">
      <div class="col">
        <div class="px-4 pt-3 bezel-header">
          <div class="row">
            <div class="col-12 col-xl-6">
              <h1 class="display-3 text-white"><em>${repo.name}</em></h1>
              ${repo.description ? '<p class="text-white fs-4">' + repo.description + '</p>' : ''}
            </div>
            <div class="col-12 col-xl-6 d-flex flex-column justify-content-around">
              <div class="row flex-grow-1 align-items-stretch language-percent-row">
                <div class="col-12 d-flex align-items-stretch">
                  <div class="d-flex flex-grow-1 flex-nowrap">
                    ${topLanguagePercentages.map((percentTuple) => `<div class='language-col flex-grow-1 overflow-hidden'><div class="language-name text-light font-monospace">${percentTuple[0]}</div><div class="language-percent" style="flex-grow: ${percentTuple[1] / largestPercent}"></div></div>`).join('')}
                  <div class='language-col flex-grow-1 overflow-hidden'><div class="language-name text-light font-monospace">other</div><div class="language-percent" style="flex-grow: ${otherLanguagePercent / largestPercent}"></div></div>
                  </div>
                </div>
              </div>
              <div class="row align-items-center">
                <div class="col-12">
                  <div class="header-button-container">
                    <button class="btn btn-info btn-lg dropdown-toggle clone-popover-btn">Clone</button>
                    ${nav.homepageButtons.map((buttonConfig) => {
                      return `<a class="btn btn-outline-info btn-lg shadow-none" href="${buttonConfig.url}" ${buttonConfig.newTab ? 'target="_blank"' : ''}>${buttonConfig.text}${buttonConfig.newTab ? ' <span>&#x29C9;</span>' : ''}</a>`
                    }).join('')}
                  </div>
                </div>
              </div>
            </div>
          </div>
          <noscript>
            <div class="row mt-2">
              <div class="col">
                <p class="font-monospace text-white">
                  Clone URL: ${repo.cloneUrl}
                </p>
              </div>
            </div>
          </noscript>
          <div class="row mt-2">
            <div class="col">
              <p class="font-monospace text-white mb-2 d-inline-block"><a class="btn btn-outline-info badge shadow-none me-2" href="${nav.repoCurrentBranchRssFeed()}">
                <img src="${nav.rootPath()}frontend/img/rss-icon.svg" style="width: 11px; margin-right: 5px;" />RSS
              </a>Latest commit: ${latestCommit.date.toDateString()} <a class="fw-bold link-info" href="${nav.repoBranchCommitsBase()}${latestCommit.hash}">${latestCommit.hash.substr(0, 6)}</a> ${latestCommitMessage}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="row my-4 mx-1">
      <div class="col">
        ${await renderContentIfAvailable(await getReadMe(repo.name, branch.name), branch.name)}
      </div>
    </div>
  `
}
