package local

import (
	"context"
	"fmt"
	"io"
	"os"
	"path/filepath"

	"gitlink.org.cn/cloudream/common/utils/os2"
	clitypes "gitlink.org.cn/cloudream/jcs-pub/client/types"
	"gitlink.org.cn/cloudream/jcs-pub/common/pkgs/storage/types"
	cortypes "gitlink.org.cn/cloudream/jcs-pub/coordinator/types"
)

type S2STransfer struct {
	feat    *cortypes.S2STransferFeature
	detail  *clitypes.UserSpaceDetail
	dstPath string
}

// 只有同一个机器的存储之间才可以进行数据直传
func (s *S2STransfer) CanTransfer(src *clitypes.UserSpaceDetail) bool {
	_, ok := src.Storage.Type.(*cortypes.LocalStorageType)
	if !ok {
		return false
	}

	if src.Storage.MasterHub != s.detail.Storage.MasterHub {
		return false
	}

	return true
}

// 执行数据直传
func (s *S2STransfer) Transfer(ctx context.Context, src *clitypes.UserSpaceDetail, srcPath string, opt types.S2SOption) (string, error) {
	absTempDir, err := filepath.Abs(s.feat.TempDir)
	if err != nil {
		return "", fmt.Errorf("get abs temp dir %v: %v", s.feat.TempDir, err)
	}

	s.dstPath = opt.DestPathHint
	if s.dstPath == "" {
		s.dstPath = filepath.Join(absTempDir, os2.GenerateRandomFileName(10))
	}

	copy, err := os.OpenFile(s.dstPath, os.O_WRONLY|os.O_CREATE, 0644)
	if err != nil {
		return "", err
	}
	defer copy.Close()

	srcFile, err := os.Open(srcPath)
	if err != nil {
		return "", err
	}
	defer srcFile.Close()

	_, err = io.Copy(copy, srcFile)
	if err != nil {
		return "", err
	}

	return s.dstPath, nil
}

func (s *S2STransfer) Complete() {

}

func (s *S2STransfer) Abort() {
	if s.dstPath != "" {
		os.Remove(s.dstPath)
	}
}
