package repo

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

	repo_model "code.gitea.io/gitea/models/repo"
	"code.gitea.io/gitea/modules/context"
	code_indexer "code.gitea.io/gitea/modules/indexer/code"

	"code.gitea.io/gitea/modules/setting"
)

func Code(ctx *context.APIContext) {
	language := ctx.FormString("language")
	keyword := ctx.FormString("keyword")
	queryType := ctx.FormString("query_type")
	isMatch := queryType == "match"

	page := ctx.FormInt("page")
	if page <= 0 {
		page = 1
	}

	var (
		total                 int
		searchResults         []*code_indexer.Result
		searchResultLanguages []*code_indexer.SearchResultLanguages
	)

	var codeIndexerUnavailable bool
	var repoMaps map[int64]*repo_model.Repository

	total, searchResults, searchResultLanguages, err := code_indexer.PerformSearch(ctx, []int64{ctx.Repo.Repository.ID},
		language, keyword, page, setting.UI.RepoSearchPagingNum, isMatch)
	if err != nil {
		if code_indexer.IsAvailable(ctx) {
			ctx.Error(http.StatusInternalServerError, "SearchResults", err)
			return
		}
		codeIndexerUnavailable = true
	} else {
		codeIndexerUnavailable = !code_indexer.IsAvailable(ctx)
	}

	pageCount := int(math.Ceil(float64(total) / float64(setting.UI.RepoSearchPagingNum)))
	ctx.Resp.Header().Set("X-Page", strconv.Itoa(page))
	ctx.Resp.Header().Set("X-PerPage", strconv.Itoa(setting.UI.RepoSearchPagingNum))
	ctx.Resp.Header().Set("X-Total", strconv.FormatInt(int64(total), 10))
	ctx.Resp.Header().Set("X-PageCount", strconv.Itoa(pageCount))
	ctx.Resp.Header().Set("X-HasMore", strconv.FormatBool(page < pageCount))

	ctx.SetLinkHeader(int(total), setting.UI.RepoSearchPagingNum)
	ctx.Resp.Header().Set("X-Total-Count", fmt.Sprintf("%d", total))
	ctx.JSON(http.StatusOK, struct {
		CodeIndexerUnavailable bool
		RepoMaps               map[int64]*repo_model.Repository
		SearchResults          []*code_indexer.Result
		SearchResultLanguages  []*code_indexer.SearchResultLanguages
	}{
		CodeIndexerUnavailable: codeIndexerUnavailable,
		RepoMaps:               repoMaps,
		SearchResults:          searchResults,
		SearchResultLanguages:  searchResultLanguages,
	})
}
