// 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 org

import (
	"gitote/gitote/models"
	"gitote/gitote/pkg/context"
	"gitote/gitote/pkg/form"
	"gitote/gitote/pkg/setting"

	log "gopkg.in/clog.v1"
)

const (
	// CreateTPL organization page template
	CreateTPL = "org/create"
)

// Create renders the page to create an organization
func Create(c *context.Context) {
	c.Data["Title"] = c.Tr("new_org")
	c.HTML(200, CreateTPL)
}

// CreatePost creates an organization with the body fields
func CreatePost(c *context.Context, f form.CreateOrg) {
	c.Data["Title"] = c.Tr("new_org")

	if c.HasError() {
		c.HTML(200, CreateTPL)
		return
	}

	org := &models.User{
		Name:     f.OrgName,
		IsActive: true,
		Type:     models.UserTypeOrganization,
	}

	// Create organization
	if err := models.CreateOrganization(org, c.User); err != nil {
		c.Data["Err_OrgName"] = true
		switch {
		case models.IsErrUserAlreadyExist(err):
			c.RenderWithErr(c.Tr("form.org_name_been_taken"), CreateTPL, &f)
		case models.IsErrNameReserved(err):
			c.RenderWithErr(c.Tr("org.form.name_reserved", err.(models.ErrNameReserved).Name), CreateTPL, &f)
		case models.IsErrNamePatternNotAllowed(err):
			c.RenderWithErr(c.Tr("org.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), CreateTPL, &f)
		default:
			c.Handle(500, "CreateOrganization", err)
		}
		return
	}
	log.Trace("Organization created: %s", org.Name)

	c.Redirect(setting.AppSubURL + "/org/" + f.OrgName + "/dashboard")
}
