package repo

import (
	"math"
	"net/http"
	"strconv"
	"strings"

	"code.gitea.io/gitea/modules/context"
	"code.gitea.io/gitea/modules/log"
	"code.gitea.io/gitea/routers/api/v1/utils"
	"code.gitlink.org.cn/Gitlink/gitea_hat.git/modules/convert"
	"code.gitlink.org.cn/Gitlink/gitea_hat.git/modules/structs"
)

func ListTags(ctx *context.APIContext) {
	listOpts := utils.GetListOptions(ctx)

	tags, total, err := ctx.Repo.GitRepo.GetTagInfos(listOpts.Page, listOpts.PageSize)
	if err != nil {
		ctx.Error(http.StatusInternalServerError, "GetTags", err)
		return
	}

	apiTags := make([]*structs.Tag, len(tags))
	for i := range tags {
		convertTag, err := convert.ToTag(ctx.Repo.Repository, ctx.Repo.GitRepo, tags[i])
		if err != nil {
			ctx.Error(http.StatusInternalServerError, "convert.ToTag", err)
			return
		}
		apiTags[i] = convertTag
	}

	pageCount := int(math.Ceil(float64(total) / float64(listOpts.PageSize)))
	ctx.RespHeader().Set("X-Page", strconv.Itoa(listOpts.Page))
	ctx.RespHeader().Set("X-PerPage", strconv.Itoa(listOpts.PageSize))
	ctx.RespHeader().Set("X-Total", strconv.Itoa(total))
	ctx.RespHeader().Set("X-PageCount", strconv.Itoa(pageCount))
	ctx.RespHeader().Set("X-HasMore", strconv.FormatBool(listOpts.Page < pageCount))

	ctx.SetLinkHeader(total, listOpts.PageSize)
	ctx.SetTotalCountHeader(int64(total))
	ctx.JSON(http.StatusOK, &apiTags)
}

func BranchNameSet(ctx *context.APIContext) {

	searchName := ctx.Params("name")
	branches, _, err := ctx.Repo.GitRepo.GetBranchNames(0, 0) //get count of the branch
	if err != nil {
		ctx.ServerError("GetBranches", err)
		return
	}

	if searchName == "" {
		ctx.JSON(http.StatusOK, branches)
	} else {
		var branchNameSet []string
		for _, branch := range branches {

			log.Info("branch is \n", branch)
			if strings.Contains(branch, searchName) {
				branchNameSet = append(branchNameSet, branch)
			}
		}
		ctx.JSON(http.StatusOK, branchNameSet)
	}
}

func TagNameSet(ctx *context.APIContext) {

	searchName := ctx.Params("name")

	tags, err := ctx.Repo.GitRepo.GetTags(0, 0)
	if err != nil {
		ctx.ServerError("GetTags", err)
		return
	}

	if searchName == "" {
		ctx.JSON(http.StatusOK, tags)
	} else {
		var tagNameSet []string
		for _, tag := range tags {

			log.Info("tag is \n", tag)
			if strings.Contains(tag, searchName) {
				tagNameSet = append(tagNameSet, tag)
			}
		}
		ctx.JSON(http.StatusOK, tagNameSet)
	}

}
