package dataset

import (
	"code.gitea.io/gitea/models"
	"code.gitea.io/gitea/modules/auth"
	"code.gitea.io/gitea/modules/base"
	"code.gitea.io/gitea/modules/context"
	"code.gitea.io/gitea/modules/log"
	"code.gitea.io/gitea/modules/setting"
)

const (
	tplDataSet base.TplName = "datasets/index"
	tplCreate  base.TplName = "datasets/create"
)

func MyList(ctx *context.Context) {
	log.Debug("[dataset] mylist...\n")
	ctx.HTML(200, tplDataSet)
}

func Create(ctx *context.Context) {
	log.Debug("[dataset] Create...\n")
	ctx.HTML(200, tplCreate)
}

// func handleCreateError(ctx *context.Context, owner *models.User, err error, name string, tpl base.TplName, form interface{}) {
// 	switch {
// 	case models.IsErrReachLimitOfRepo(err):
// 		ctx.RenderWithErr(ctx.Tr("repo.form.reach_limit_of_creation", owner.MaxCreationLimit()), tpl, form)
// 	case models.IsErrRepoAlreadyExist(err):
// 		ctx.Data["Err_RepoName"] = true
// 		ctx.RenderWithErr(ctx.Tr("form.repo_name_been_taken"), tpl, form)
// 	case models.IsErrNameReserved(err):
// 		ctx.Data["Err_RepoName"] = true
// 		ctx.RenderWithErr(ctx.Tr("repo.form.name_reserved", err.(models.ErrNameReserved).Name), tpl, form)
// 	case models.IsErrNamePatternNotAllowed(err):
// 		ctx.Data["Err_RepoName"] = true
// 		ctx.RenderWithErr(ctx.Tr("repo.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tpl, form)
// 	default:
// 		ctx.ServerError(name, err)
// 	}
// }

func CreatePost(ctx *context.Context, form auth.CreateDatasetForm) {
	ctx.Data["Title"] = ctx.Tr("new_dataset")

	ctxUser := ctx.User

	if ctx.HasError() {
		ctx.HTML(200, tplCreate)
		return
	}

	var err error
	opts := models.Dataset{
		Title:       form.Title,
		Category:    form.Category,
		Description: form.Description,
		License:     form.License,
		Task:        form.Task,
		ReleaseID:   form.ReleaseID,
		UserID:      ctxUser.ID,
		Status:      0,
	}
	// if !opts.IsValid() {
	// 	ctx.RenderWithErr(ctx.Tr("repo.template.one_item"), tplCreate, form)
	// 	return
	// }

	if err = models.CreateDataset(&opts); err != nil {
		log.Error("%v", err)
	}

	var attachmentUUIDs []string
	if setting.Attachment.Enabled {
		attachmentUUIDs = form.Files
	}

	log.Error("%v", attachmentUUIDs)

	if err = models.AddDatasetAttachments(opts.ID, attachmentUUIDs); err != nil {
		log.Error("%v", err)
	}

	if err == nil {
		log.Trace("Dataset created [%d]: %s/%s", opts.ID, ctxUser.Name, opts.Title)
		ctx.Redirect(setting.AppSubURL + "/datasets")
		return
	}

	// handleCreateError(ctx, ctxUser, err, "CreatePost", tplCreate, &form)
}

func Delete(ctx *context.Context) {
	log.Debug("[dataset] Delete...\n")
}
