package api

import (
	"copter-train/db/model"
	"copter-train/db/repo"
	"copter-train/log"
	"errors"
	"time"

	"github.com/gin-gonic/gin"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
)

// 具体数据库中创建
// 每个用户每个模块有多条记录,每次学习生成一条记录
func CreateLearnLog(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	db := c.Param("scope")
	if len(db) == 0 {
		return nil, errors.New("scope不能为空")
	}
	learnLog := &model.LearnLog{}
	err := c.ShouldBindJSON(learnLog)
	if err != nil {
		log.Error(err)
		return nil, err
	}
	if len(learnLog.Cid) < 1 {
		return nil, errors.New("模块id不能为空")
	}

	// 没找到数据，创建
	learnLog.Uid = apictx.User.ID
	zero := 0
	learnLog.LearnTime = &zero
	learnLog.CreateTime = time.Now()
	learnLog.UpdateTime = time.Now()
	return repo.RepoAddDbDoc(apictx.CreateRepoCtx(), db, repo.CollectionLearnLog, learnLog)
}

// 每分钟记录下学习时长
// sync/time/:id/:scope
func SyncLearnTime(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	id := c.Param("id")
	db := c.Param("scope")
	objId, _ := primitive.ObjectIDFromHex(id)
	if objId.IsZero() {
		return nil, errors.New("id错误")
	}
	update := bson.M{"$inc": bson.M{"learnTime": 1}, "$set": bson.M{"updateTime": time.Now()}}
	return repo.RepoUpdateSetDbDocProps(apictx.CreateRepoCtx(), db, repo.CollectionLearnLog, id, update)
}
