package rpc

import (
	"context"

	"gitlink.org.cn/cloudream/common/consts/errorcode"
	"gitlink.org.cn/cloudream/common/pkgs/logger"
	"gitlink.org.cn/cloudream/jcs-pub/common/pkgs/rpc"
	hubrpc "gitlink.org.cn/cloudream/jcs-pub/common/pkgs/rpc/hub"
)

func (svc *Service) PublicStoreListAll(context context.Context, msg *hubrpc.PublicStoreListAll) (*hubrpc.PublicStoreListAllResp, *rpc.CodeError) {
	pub, err := svc.stgPool.GetPublicStore(&msg.UserSpace)
	if err != nil {
		return nil, rpc.Failed(errorcode.OperationFailed, err.Error())
	}

	es, err := pub.ListAll(msg.Path)
	if err != nil {
		return nil, rpc.Failed(errorcode.OperationFailed, err.Error())
	}

	return &hubrpc.PublicStoreListAllResp{
		Entries: es,
	}, nil
}

func (svc *Service) PublicStoreMkdirs(context context.Context, msg *hubrpc.PublicStoreMkdirs) (*hubrpc.PublicStoreMkdirsResp, *rpc.CodeError) {
	pub, err := svc.stgPool.GetPublicStore(&msg.UserSpace)
	if err != nil {
		return nil, rpc.Failed(errorcode.OperationFailed, err.Error())
	}

	var suc []bool
	for _, p := range msg.Pathes {
		if err := pub.Mkdir(p); err != nil {
			suc = append(suc, false)
			logger.Warnf("userspace %v mkdir %s: %v", msg.UserSpace, p, err)
		} else {
			suc = append(suc, true)
		}
	}

	return &hubrpc.PublicStoreMkdirsResp{
		Successes: suc,
	}, nil
}
