import m from 'mithril'
import htmlPage from './common/htmlPage.ts'

export default async (reposConfig: any, eleventyConfig: any, data: any) => {
  const isDirectory = eleventyConfig.getFilter("isDirectory")
  const topLevelFilesOnly = eleventyConfig.getFilter("topLevelFilesOnly")
  const getDirectoryContents = eleventyConfig.getFilter("getDirectoryContents")
  const getFileContents = eleventyConfig.getFilter("getFileContents")
  const getFileLastTouchInfo = eleventyConfig.getFilter("getFileLastTouchInfo")
  const getRelativePath = eleventyConfig.getFilter("getRelativePath")
  const slugify = eleventyConfig.getFilter("slugify")
  const lineNumbers = eleventyConfig.getFilter("lineNumbers")
  const highlightCode = eleventyConfig.getFilter("highlightCode")
  const languageExtension = eleventyConfig.getFilter("languageExtension")
  const renderContentIfAvailable = eleventyConfig.getFilter("renderContentIfAvailable")

  const pageContent = [
    m('div', {class: "row mt-3 mb-1"},
      m('div', {class: "col"},
        m('p', [
          'Files snapshot from ',
          m('span', {class: "font-monospace"}, data.fileInfo.branchName)
        ])
      )
    ),
    m('div', {class: "directory-buttons row"},
      m('div', {class: "col"},
        m('h3', [
          m('span', {class: "bezel-gray p-1 my-1 d-inline-block"},
            m('a', {href: `${data.reposPath}/${data.fileInfo.repoName}/branches/${data.fileInfo.branchName}/files`}, './')
          ),
          data.fileInfo.file.split('/').map((dir, index, arr) => {
            if (index === arr.length - 1) {
              return m('span', {class: "px-2 my-1 d-inline-block"}, dir)
            }
            else {
              return m('span', {class: "bezel-gray p-1 my-1 d-inline-block"}, [
                m('a', {
                  href: `${data.reposPath}/${data.fileInfo.repoName}/branches/${data.fileInfo.branchName}/files/${arr.slice(0, index + 1).map((part) => slugify(part)).join('/')}.html`}, `${dir}/`)
              ])
            }
          })
        ])
      )
    ),
    (isDirectory(data.fileInfo.file, data.fileInfo.repoName, data.fileInfo.branchName) ?
      m('div', {class: "row"},
        m('div', {class: "col"},
          m('ul', {class: "list-group"},
            topLevelFilesOnly(getDirectoryContents(data.fileInfo.repoName, data.fileInfo.branchName, data.fileInfo.file), data.fileInfo.file + '/').map((dir) => {
              return m('li', {class: 'list-group-item'}, [
                dir.isDirectory ? m('span', m.trust('&#x1F4C1;&nbsp;')) : null,
                m('a', {
                  href: `${data.reposPath}/${slugify(data.fileInfo.repoName)}/branches/${slugify(data.fileInfo.branchName)}/files/${dir.fullPath.split('/').map((pathPart) => {
                    return pathPart.split('.').map((subPart) => {
                      return slugify(subPart)
                    }).join('.')
                  }).join('/')}.html`},
                  getRelativePath(data.fileInfo.file, dir.name)
                )
              ])
            })
          )
        )
      )
    : [
        m('div', {class: "row my-3"},
          m('div', {class: "col"},
            m('span', m('a', {
              href: `${data.reposPath}/${slugify(data.fileInfo.repoName)}/branches/${slugify(data.fileInfo.branchName)}/raw/${data.fileInfo.file.split('.').map(filePart => slugify(filePart)).join('.')}`}, 'View raw file'))
          )
        ),
        (data.fileInfo.file.endsWith(".md") ?
          [
            m('div', {class: "row my-2"},
              m('div', {class: "col"},
                m('div', {class: "form-check form-switch"}, [
                  m('input', {
                    class: "form-check-input",
                    type: "checkbox",
                    role: "switch",
                    id: "showRenderedContent",
                    checked: true
                  }),
                  m('label', {
                    class: "form-check-label",
                    for: "showRenderedContent"
                  }, 'Show rendered markdown')
                ])
              )
            ),
            m('div', {class: "row rendered-content"},
              m('div', {class: "col"},
                m.trust(await renderContentIfAvailable(await getFileContents(
                  data.fileInfo.repoName,
                  data.fileInfo.branchName,
                  data.fileInfo.file
                ), data.fileInfo.branchName)
              ))
            )
          ]
        : null),
        m('div', {class: `row code-content ${data.fileInfo.file.endsWith('.md') ? 'd-none' : ''}`},
          m('div', {class: "col"}, [
            m('div', {class: "row"},
              m('div', {class: "col-auto"},
                m('div', {class: "form-check form-switch"}, [
                  m('input', {class: "form-check-input", type: "checkbox", role: "switch", id: "showLastTouch"}),
                  m('label', {class: "form-check-label", for: "showLastTouch"}, 'Show last line change'),
                ])
              )
            ),
            m('div', {class: "row"}, [
              m('div', {class: "col-auto p-0"},
                m('code', {style: "white-space: pre;"},
                  m('pre', {class: "language-text"},
                    lineNumbers(await getFileContents(data.fileInfo.repoName, data.fileInfo.branchName, data.fileInfo.file)).map((lineNumber) => {
                      return lineNumber
                    }).join('\n')
                  )
                )
              ),
              m('div', {id: "annotations", class: "col-auto d-none p-0"},
                m('code', {style: "white-space: pre;"}, [
                  m('pre', {class: "language-text"}, m.trust(
                    (await getFileLastTouchInfo(
                      data.fileInfo.repoName,
                      data.fileInfo.branchName,
                      data.fileInfo.file
                    )).map((annotation) => {
                      return `<a href="${data.reposPath}/${slugify(data.fileInfo.repoName)}/branches/${slugify(data.fileInfo.branchName)}/commits/${annotation.sha}">${annotation.sha.substr(0, 6)}</a> ${annotation.author}`
                    }).join('\n')))
                ])
              ),
              m('div', {class: "col overflow-scroll p-0"},
                m('code', m.trust(highlightCode(
                  await getFileContents(
                    data.fileInfo.repoName,
                    data.fileInfo.branchName,
                    data.fileInfo.file
                  ),
                  languageExtension(
                    data.fileInfo.file,
                    data.fileInfo.repoName
                  )
                )))
              )
            ])
          ])
        ),
        m('script', {type: "text/javascript"},
          `
          const toggleLastTouch = (event) => {
            const isOn = event.target.checked
            const annotations = document.getElementById("annotations")
            if (isOn) {
              annotations.classList.remove("d-none")
            } else {
              annotations.classList.add("d-none")
            }
          }

          document.getElementById("showLastTouch")?.addEventListener('click', toggleLastTouch)
          `
        )
      ]
    )
  ]

  return await htmlPage(reposConfig, eleventyConfig, data, pageContent)
}
