// Copyright 2015 - Present, The Gogs Authors. All rights reserved.
// Copyright 2018 - Present, Gitote. All rights reserved.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.

package admin

import (
	"gitote/gitote/models"
	"gitote/gitote/pkg/context"
	"gitote/gitote/routes/api/v1/convert"
	"gitote/gitote/routes/api/v1/user"

	api "gitlab.com/gitote/go-gitote-client"
)

// CreateTeam api for create a team
func CreateTeam(c *context.APIContext, form api.CreateTeamOption) {
	team := &models.Team{
		OrgID:       c.Org.Organization.ID,
		Name:        form.Name,
		Description: form.Description,
		Authorize:   models.ParseAccessMode(form.Permission),
	}
	if err := models.NewTeam(team); err != nil {
		if models.IsErrTeamAlreadyExist(err) {
			c.Error(422, "", err)
		} else {
			c.Error(500, "NewTeam", err)
		}
		return
	}

	c.JSON(201, convert.ToTeam(team))
}

// AddTeamMember api for add a member to a team
func AddTeamMember(c *context.APIContext) {
	u := user.GetUserByParams(c)
	if c.Written() {
		return
	}
	if err := c.Org.Team.AddMember(u.ID); err != nil {
		c.Error(500, "AddMember", err)
		return
	}

	c.Status(204)
}

// RemoveTeamMember api for remove one member from a team
func RemoveTeamMember(c *context.APIContext) {
	u := user.GetUserByParams(c)
	if c.Written() {
		return
	}

	if err := c.Org.Team.RemoveMember(u.ID); err != nil {
		c.Error(500, "RemoveMember", err)
		return
	}

	c.Status(204)
}
