package repo

import (
	"net/http"

	repo_model "code.gitea.io/gitea/models/repo"
	"code.gitea.io/gitea/modules/context"
	"code.gitea.io/gitea/modules/git"
	api "code.gitea.io/gitea/modules/structs"
	util "code.gitea.io/gitea/modules/util"
	wiki_service "code.gitea.io/gitea/services/wiki"
)

func ListWikiPageNames(ctx *context.APIContext) {

	wikiRepo, err := git.OpenRepository(ctx, ctx.Repo.Repository.WikiPath())
	if err != nil {
		if git.IsErrNotExist(err) || err.Error() == "no such file or directory" {
			ctx.NotFound(err)
		} else {
			ctx.Error(http.StatusInternalServerError, "OpenRepository", err)
		}
		return
	}

	commit, err := wikiRepo.GetBranchCommit("master")
	if err != nil {
		if git.IsErrNotExist(err) {
			ctx.NotFound(err)
		} else {
			ctx.Error(http.StatusInternalServerError, "GetBranchCommit", err)
		}
		return
	}

	if wikiRepo != nil {

		defer wikiRepo.Close()
	}

	if ctx.Written() {
		return
	}

	entries, err := commit.ListEntries()
	if err != nil {
		ctx.ServerError("ListEntries", err)
		return
	}

	pages := make([]*api.WikiPageMetaData, 0, len(entries))
	for _, entry := range entries {
		if !entry.IsRegular() {
			continue
		}
		wikiName, err := wiki_service.GitPathToWebPath(entry.Name())
		if err != nil {
			if repo_model.IsErrWikiInvalidFileName(err) {
				continue
			}
			ctx.Error(http.StatusInternalServerError, "WikiFilenameToName", err)
			return
		}
		subURL := string(wikiName)
		_, title := wiki_service.WebPathToUserTitle(wikiName)
		pages = append(pages, &api.WikiPageMetaData{
			Title:   title,
			HTMLURL: util.URLJoin(ctx.Repo.Repository.HTMLURL(), "wiki", subURL),
			SubURL:  subURL,
		})
	}

	ctx.SetTotalCountHeader(int64(len(entries)))
	ctx.JSON(http.StatusOK, pages)
}
