package repo

import (
	"bytes"
	"io"
	"net/http"
	"net/url"
	"sort"
	"strings"

	repo_model "code.gitea.io/gitea/models/repo"

	"code.gitea.io/gitea/modules/context"
	"code.gitea.io/gitea/modules/git"
	"code.gitea.io/gitea/modules/markup"
	"code.gitea.io/gitea/modules/markup/markdown"
	"code.gitea.io/gitea/modules/web"
	wiki_service "code.gitea.io/gitea/services/wiki"
	hat_git "code.gitlink.org.cn/Gitlink/gitea_hat.git/modules/git"
	hat_api "code.gitlink.org.cn/Gitlink/gitea_hat.git/modules/structs"
)

func ListWikiPages(ctx *context.APIContext) {
	if !ctx.Repo.Repository.HasWiki() {
		return
	}

	wikiCloneWiki := ctx.Repo.Repository.WikiCloneLink()
	wikiRepo, commit, err := findWikiRepoCommit(ctx.Context)
	defer func() {
		if wikiRepo != nil {
			wikiRepo.Close()
		}
	}()
	if err != nil {
		ctx.ServerError("findWikiRepoCommit", err)
		return
	}

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

	pages := make([]hat_api.WikiesResponse, 0, len(entries))
	for _, entry := range entries {
		if !entry.IsRegular() {
			continue
		}
		lastCommit, firstCommit, err := hat_git.GetFirstAndLastCommitByPath(wikiRepo, "master", entry.Name())
		if err != nil {
			ctx.ServerError("GetCommitByPath", err)
			return
		}
		wikiName, err := wiki_service.FilenameToName(entry.Name())
		if err != nil {
			if repo_model.IsErrWikiInvalidFileName(err) {
				continue
			}
			ctx.ServerError("wiki_service.FilenameToName", err)
			return
		}
		pages = append(pages, hat_api.WikiesResponse{
			WikiCloneLink: hat_api.CloneLink{
				HTTPS: wikiCloneWiki.HTTPS,
				SSH:   wikiCloneWiki.SSH,
			},
			WikiMeta: hat_api.WikiMeta{
				Name: wikiName,
				Commit: hat_api.WikiCommit{
					Author: hat_api.WikiUser{
						Name:  lastCommit.Author.Name,
						Email: lastCommit.Author.Email,
						When:  lastCommit.Author.When.Unix(),
					},
					Commiter: hat_api.WikiUser{
						Name:  lastCommit.Committer.Name,
						Email: lastCommit.Committer.Email,
						When:  lastCommit.Author.When.Unix(),
					},
					ID:      lastCommit.ID.String(),
					Message: lastCommit.Message(),
				},
				FirstCommit: hat_api.WikiCommit{
					Author: hat_api.WikiUser{
						Name:  firstCommit.Author.Name,
						Email: firstCommit.Author.Email,
						When:  firstCommit.Author.When.Unix(),
					},
					Commiter: hat_api.WikiUser{
						Name:  firstCommit.Committer.Name,
						Email: firstCommit.Committer.Email,
						When:  firstCommit.Author.When.Unix(),
					},
					ID:      firstCommit.ID.String(),
					Message: firstCommit.Message(),
				},
			},
		})
	}

	sort.Slice(pages, func(i, j int) bool {
		return pages[i].FirstCommit.Author.When > pages[j].FirstCommit.Author.When
	})

	ctx.JSON(http.StatusOK, pages)
}

func findWikiRepoCommit(ctx *context.Context) (*git.Repository, *git.Commit, error) {
	wikiRepo, err := git.OpenRepository(ctx, ctx.Repo.Repository.WikiPath())
	if err != nil {
		ctx.ServerError("OpenRepository", err)
		return nil, nil, err
	}

	commit, err := wikiRepo.GetBranchCommit("master")
	if err != nil {
		return wikiRepo, nil, err
	}
	return wikiRepo, commit, nil
}

func CreateWiki(ctx *context.Context) {
	form := web.GetForm(ctx).(*hat_api.WikiOption)

	wikiName := wiki_service.NormalizeWikiName(form.Name)
	wikiCloneLink := ctx.Repo.Repository.WikiCloneLink()

	if err := wiki_service.AddWikiPage(ctx, ctx.Doer, ctx.Repo.Repository, wikiName, form.Content, form.CommitMessage); err != nil {
		if repo_model.IsErrWikiReservedName(err) {
			ctx.Error(http.StatusInternalServerError, "WikiNameIsReservedPage", "wiki名称是被保留的.")
		} else if repo_model.IsErrWikiAlreadyExist(err) {
			ctx.Error(http.StatusConflict, "WikiNameAlreadyExist", "wiki名称已存在")
		} else {
			ctx.Error(http.StatusInternalServerError, "AddWikiPage", err.Error())
		}
		return
	}

	wikiRepo, commit, _ := findWikiRepoCommit(ctx)
	data, entry, pageFilename := wikiContentsByName(ctx, commit, wikiName)
	metas := ctx.Repo.Repository.ComposeDocumentMetas()

	var rctx = &markup.RenderContext{
		URLPrefix: ctx.Repo.RepoLink,
		Metas:     metas,
		IsWiki:    true,
	}

	var buf strings.Builder
	if err := markdown.Render(rctx, bytes.NewReader(data), &buf); err != nil {
		if wikiRepo != nil {
			wikiRepo.Close()
		}
		ctx.ServerError("Render", err)
		return
	}

	commitsCount, _ := wikiRepo.FileCommitsCount("master", pageFilename)
	c, err := wikiRepo.GetCommitByPath(entry.Name())
	if err != nil {
		if repo_model.IsErrWikiInvalidFileName(err) {
			return
		}
	}
	wiki := hat_api.WikiResponse{
		WikiCloneLink: hat_api.CloneLink{
			HTTPS: wikiCloneLink.HTTPS,
			SSH:   wikiCloneLink.SSH,
		},
		WikiMeta: hat_api.WikiMeta{
			Name: form.Name,
			Commit: hat_api.WikiCommit{
				Author: hat_api.WikiUser{
					Name:  c.Author.Name,
					Email: c.Author.Email,
					When:  c.Author.When.Unix(),
				},
				Commiter: hat_api.WikiUser{
					Name:  c.Committer.Name,
					Email: c.Committer.Email,
					When:  c.Author.When.Unix(),
				},
				ID:      c.ID.String(),
				Message: c.Message(),
			},
		},
		CommitCounts:  commitsCount,
		MdContent:     string(data),
		SimpleContent: buf.String(),
	}
	ctx.JSON(http.StatusOK, wiki)
}

func wikiContentsByEntry(ctx *context.Context, entry *git.TreeEntry) []byte {
	reader, err := entry.Blob().DataAsync()
	if err != nil {
		ctx.ServerError("Blob.Data", err)
		return nil
	}
	defer reader.Close()
	content, err := io.ReadAll(reader)
	if err != nil {
		ctx.ServerError("ReadAll", err)
		return nil
	}
	return content
}

func findEntryForFile(commit *git.Commit, target string) (*git.TreeEntry, error) {
	entry, err := commit.GetTreeEntryByPath(target)
	if err != nil {
		return nil, err
	}
	if entry != nil {
		return entry, nil
	}

	// Then the unescaped, shortest alternative
	var unescapedTarget string
	if unescapedTarget, err = url.QueryUnescape(target); err != nil {
		return nil, err
	}
	return commit.GetTreeEntryByPath(unescapedTarget)
}

// wikiContentsByName returns the contents of a wiki page, along with a boolean
// indicating whether the page exists. Writes to ctx if an error occurs.
func wikiContentsByName(ctx *context.Context, commit *git.Commit, wikiName string) ([]byte, *git.TreeEntry, string) {
	pageFilename := wiki_service.NameToFilename(wikiName)
	entry, err := findEntryForFile(commit, pageFilename)
	if err != nil {
		if git.IsErrNotExist(err) {
		} else {
			ctx.ServerError("findEntryForFile", err)
		}
		return nil, nil, ""
	}
	return wikiContentsByEntry(ctx, entry), entry, pageFilename
}

func GetWiki(ctx *context.APIContext) {
	wikiRepo, commit, _ := findWikiRepoCommit(ctx.Context)

	defer func() {
		if wikiRepo != nil {
			wikiRepo.Close()
		}
	}()

	wikiCloneWiki := ctx.Repo.Repository.WikiCloneLink()

	pageName := wiki_service.NormalizeWikiName(ctx.Params(":page"))
	if len(pageName) == 0 {
		pageName = "Home"
	}
	data, entry, pageFileName := wikiContentsByName(ctx.Context, commit, pageName)
	if entry == nil {
		ctx.NotFound()
		return
	}
	metas := ctx.Repo.Repository.ComposeDocumentMetas()
	var rctx = &markup.RenderContext{
		URLPrefix: ctx.Repo.RepoLink,
		Metas:     metas,
		IsWiki:    true,
	}
	var buf strings.Builder
	if err := markdown.Render(rctx, bytes.NewReader(data), &buf); err != nil {
		ctx.ServerError("markdown.Render", err)
		return
	}

	c, err := wikiRepo.GetCommitByPath(entry.Name())
	if err != nil {
		if repo_model.IsErrWikiInvalidFileName(err) {
			return
		}
	}
	commitsCount, _ := wikiRepo.FileCommitsCount("master", pageFileName)
	wiki := hat_api.WikiResponse{
		WikiCloneLink: hat_api.CloneLink{
			HTTPS: wikiCloneWiki.HTTPS,
			SSH:   wikiCloneWiki.SSH,
		},
		WikiMeta: hat_api.WikiMeta{
			Name: pageName,
			Commit: hat_api.WikiCommit{
				Author: hat_api.WikiUser{
					Name:  c.Author.Name,
					Email: c.Author.Email,
					When:  c.Author.When.Unix(),
				},
				Commiter: hat_api.WikiUser{
					Name:  c.Committer.Name,
					Email: c.Committer.Email,
					When:  c.Committer.When.Unix(),
				},
			},
		},
		CommitCounts:  commitsCount,
		MdContent:     string(data),
		SimpleContent: buf.String(),
	}
	ctx.JSON(http.StatusOK, wiki)
}

func EditWiki(ctx *context.APIContext) {
	form := web.GetForm(ctx).(*hat_api.WikiOption)
	oldWikiName := wiki_service.NormalizeWikiName(ctx.Params(":page"))
	newWikiName := wiki_service.NormalizeWikiName(form.Name)

	wikiRepo, commit, _ := findWikiRepoCommit(ctx.Context)

	defer func() {
		if wikiRepo != nil {
			wikiRepo.Close()
		}
	}()
	if _, entry, _ := wikiContentsByName(ctx.Context, commit, oldWikiName); entry == nil {
		ctx.Error(http.StatusNotFound, "WikiNotFound", "Wiki不存在")
		return
	}

	if _, entry, _ := wikiContentsByName(ctx.Context, commit, newWikiName); oldWikiName != newWikiName && entry != nil {
		ctx.Error(http.StatusNotFound, "WikiNameAlreadyExist", "Wiki已存在")
		return
	}

	if len(form.CommitMessage) == 0 {
		form.CommitMessage = ctx.Tr("repo.editor.update", form.Name)
	}

	if err := wiki_service.EditWikiPage(ctx.Context, ctx.Doer, ctx.Repo.Repository, oldWikiName, newWikiName, form.Content, form.CommitMessage); err != nil {
		ctx.Error(http.StatusInternalServerError, "EditWikiPage", err)
		return
	}

	_, newCommit, _ := findWikiRepoCommit(ctx.Context)
	data, entry, pageFilename := wikiContentsByName(ctx.Context, newCommit, newWikiName)
	c, err := wikiRepo.GetCommitByPath(entry.Name())
	if err != nil {
		if repo_model.IsErrWikiInvalidFileName(err) {
			return
		}
	}

	metas := ctx.Repo.Repository.ComposeDocumentMetas()

	var rctx = &markup.RenderContext{
		URLPrefix: ctx.Repo.RepoLink,
		Metas:     metas,
		IsWiki:    true,
	}

	var buf strings.Builder
	if err := markdown.Render(rctx, bytes.NewReader(data), &buf); err != nil {
		ctx.ServerError("markdown.Render", err)
		return
	}

	commitsCount, _ := wikiRepo.FileCommitsCount("master", pageFilename)
	wiki := hat_api.WikiResponse{
		WikiMeta: hat_api.WikiMeta{
			Name: form.Name,
			Commit: hat_api.WikiCommit{
				Author: hat_api.WikiUser{
					Name:  c.Author.Name,
					Email: c.Author.Email,
					When:  c.Author.When.Unix(),
				},
				Commiter: hat_api.WikiUser{
					Name:  c.Committer.Name,
					Email: c.Committer.Email,
					When:  c.Author.When.Unix(),
				},
				ID:      c.ID.String(),
				Message: c.Message(),
			},
		},
		CommitCounts:  commitsCount,
		MdContent:     string(data),
		SimpleContent: buf.String(),
	}

	ctx.JSON(http.StatusOK, wiki)
}

func DeleteWiki(ctx *context.APIContext) {
	wikiName := wiki_service.NormalizeWikiName(ctx.Params(":page"))
	if len(wikiName) == 0 {
		wikiName = "Home"
	}

	err := wiki_service.DeleteWikiPage(ctx.Context, ctx.Doer, ctx.Repo.Repository, wikiName)
	if err != nil {
		ctx.ServerError("wiki_service.DeleteWikiPage", err)
		return
	}

	ctx.Status(http.StatusNoContent)
}
