// Copyright 2014 The Gogs Authors. All rights reserved.
// Copyright 2020 The Gitea Authors.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package org

import (
	"code.gitea.io/gitea/models"
	"code.gitea.io/gitea/modules/auth"
	"code.gitea.io/gitea/modules/context"
	"errors"
	"strconv"
)

const DefaultOrgTagLimit = -1

// SubmitTags submit repos of org tag
func SubmitTags(ctx *context.Context, form auth.SubmitReposOfTagForm) {
	if !ctx.Org.IsOwner {
		ctx.ServerError("UpdateTagReposByID", errors.New("no access to submit tags"))
		return
	}
	tag := getTagFromContext(ctx)
	if ctx.Written() {
		return
	}
	if tag.Limit != DefaultOrgTagLimit && len(form.RepoList) > tag.Limit {
		ctx.ServerError("UpdateTagReposByID", errors.New("tags size over limit"))
		return
	}
	err := models.UpdateTagReposByID(tag.ID, ctx.Org.Organization.ID, form.RepoList)
	if err != nil {
		ctx.ServerError("UpdateTagReposByID", err)
		return
	}

	ctx.JSON(200, map[string]interface{}{
		"code": "00",
		"msg":  "success",
	})
}

// GetTagRepos get repos under org tag
func GetTagRepos(ctx *context.Context) {
	if !ctx.Org.IsOwner {
		ctx.ServerError("GetTagRepos", errors.New("no access to get tags"))
		return
	}
	tag := getTagFromContext(ctx)
	if ctx.Written() {
		return
	}

	r, err := models.GetTagRepos(tag.ID, ctx.Org.Organization.ID)
	if err != nil {
		ctx.ServerError("GetTagRepos", err)
		return
	}

	ctx.JSON(200, map[string]interface{}{
		"code": "00",
		"msg":  "success",
		"data": r,
	})
}

// getTagFromContext finds out tag info From context.
func getTagFromContext(ctx *context.Context) *models.OfficialTag {
	var tag *models.OfficialTag
	var err error

	tagIdStr := ctx.Query("tagId")
	if len(tagIdStr) == 0 {
		ctx.ServerError("GetTagInfo", errors.New("tag is not exist"))
		return nil
	}
	tagId, _ := strconv.ParseInt(tagIdStr, 10, 32)
	tag, err = models.GetTagByID(tagId)
	if err != nil {
		if models.IsErrTagNotExist(err) {
			ctx.NotFound("GetTagInfo", err)
		} else {
			ctx.ServerError("GetTagInfo", err)
		}
		return nil
	}

	return tag
}
