package http

import (
	"fmt"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"gitlink.org.cn/cloudream/common/consts/errorcode"
	"gitlink.org.cn/cloudream/common/pkgs/logger"
	cliapi "gitlink.org.cn/cloudream/jcs-pub/client/sdk/api"
)

type BucketService struct {
	*Server
}

func (s *Server) Bucket() *BucketService {
	return &BucketService{
		Server: s,
	}
}

func (s *BucketService) GetByName(ctx *gin.Context) {
	log := logger.WithField("HTTP", "Bucket.GetByName")

	var req cliapi.BucketGetByName
	if err := ctx.ShouldBindQuery(&req); err != nil {
		log.Warnf("binding query: %s", err.Error())
		ctx.JSON(http.StatusBadRequest, Failed(errorcode.BadArgument, "missing argument or invalid argument"))
		return
	}

	bucket, err := s.svc.BucketSvc().GetBucketByName(req.Name)
	if err != nil {
		log.Warnf("getting bucket by name: %s", err.Error())
		ctx.JSON(http.StatusOK, FailedError(err))
		return
	}

	ctx.JSON(http.StatusOK, OK(cliapi.BucketGetByNameResp{
		Bucket: bucket,
	}))
}

func (s *BucketService) Create(ctx *gin.Context) {
	log := logger.WithField("HTTP", "Bucket.Create")

	var req cliapi.BucketCreate
	if err := ctx.ShouldBindJSON(&req); err != nil {
		log.Warnf("binding body: %s", err.Error())
		ctx.JSON(http.StatusBadRequest, Failed(errorcode.BadArgument, "missing argument or invalid argument"))
		return
	}

	bucket, err := s.svc.BucketSvc().CreateBucket(req.Name, time.Now())
	if err != nil {
		log.Warnf("creating bucket: %s", err.Error())
		ctx.JSON(http.StatusOK, FailedError(err))
		return
	}

	ctx.JSON(http.StatusOK, OK(cliapi.BucketCreateResp{
		Bucket: bucket,
	}))
}

func (s *BucketService) Delete(ctx *gin.Context) {
	log := logger.WithField("HTTP", "Bucket.Delete")

	var req cliapi.BucketDelete
	if err := ctx.ShouldBindJSON(&req); err != nil {
		log.Warnf("binding body: %s", err.Error())
		ctx.JSON(http.StatusBadRequest, Failed(errorcode.BadArgument, "missing argument or invalid argument"))
		return
	}

	if err := s.svc.BucketSvc().DeleteBucket(req.BucketID); err != nil {
		log.Warnf("deleting bucket: %s", err.Error())
		ctx.JSON(http.StatusOK, Failed(errorcode.OperationFailed, "delete bucket failed"))
		return
	}

	ctx.JSON(http.StatusOK, OK(nil))
}

func (s *BucketService) ListAll(ctx *gin.Context) {
	log := logger.WithField("HTTP", "Bucket.ListAll")

	var req cliapi.BucketListAll
	if err := ctx.ShouldBindQuery(&req); err != nil {
		log.Warnf("binding query: %s", err.Error())
		ctx.JSON(http.StatusBadRequest, Failed(errorcode.BadArgument, "missing argument or invalid argument"))
		return
	}

	buckets, err := s.svc.BucketSvc().ListAllBuckets()
	if err != nil {
		log.Warnf("list all buckets: %s", err.Error())
		ctx.JSON(http.StatusOK, Failed(errorcode.OperationFailed, fmt.Sprintf("list all buckets: %v", err)))
		return
	}

	ctx.JSON(http.StatusOK, OK(cliapi.BucketListAllResp{
		Buckets: buckets,
	}))
}
