package user

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"
	"code.gitea.io/gitea/modules/timeutil"

	hat_activities_models "code.gitlink.org.cn/Gitlink/gitea_hat.git/models/activities"
)

func GetUserHeatmapData(ctx *context.APIContext) {
	startAt := timeutil.TimeStamp(ctx.FormInt("start"))
	endAt := timeutil.TimeStamp(ctx.FormInt("end"))
	if startAt <= 0 || endAt <= 0 {
		startAt = timeutil.TimeStampNow() - 31536000
		endAt = timeutil.TimeStampNow()
	}

	heatmap, err := hat_activities_models.GetUserHeatmapDataByTimestampRange(ctx.ContextUser, nil, ctx.Doer, startAt, endAt)
	if err != nil {
		ctx.Error(http.StatusInternalServerError, "GetUserHeatmapDataByTimestampRange", err)
		return
	}

	ctx.JSON(http.StatusOK, heatmap)

}

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 (
		repoIDs []int64
		err     error
	)

	repoIDs, err = repo_model.FindUserCodeAccessibleOwnerRepoIDs(ctx, ctx.ContextUser.ID, ctx.Doer)
	if err != nil {
		ctx.Error(http.StatusInternalServerError, "FindUserCodeAccessibleOwnerRepoIDs", err)
		return
	}

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

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

	if len(repoIDs) > 0 {
		total, searchResults, searchResultLanguages, err = code_indexer.PerformSearch(ctx, repoIDs, 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)
		}

		loadRepoIDs := make([]int64, 0, len(searchResults))
		for _, result := range searchResults {
			var find bool
			for _, id := range loadRepoIDs {
				if id == result.RepoID {
					find = true
					break
				}
			}
			if !find {
				loadRepoIDs = append(loadRepoIDs, result.RepoID)
			}
		}

		repoMaps, err := repo_model.GetRepositoriesMapByIDs(loadRepoIDs)
		if err != nil {
			ctx.Error(http.StatusInternalServerError, "GetRepositoriesMapByIDs", err)
			return
		}

		repoMaps = repoMaps
	}

	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,
	})
}
