package fileutils

import (
	"os"
	"path/filepath"
	"testing"
)

const (
	testDirRelativePath = "./test_dir"
)

func TestPathExists(t *testing.T) {
	exist := PathExists("../fileutils")
	if !exist {
		t.Fatal("应该存在的目录不存在")
	}

	exist = PathExists("foo")
	if exist {
		t.Fatal("不应该存在的目录存在")
	}
}

func TestGetDirFiles(t *testing.T) {
	checkTestDir(t, testDirRelativePath)
}

func TestZip(t *testing.T) {
	zipFileRelativePath := "test.zip"
	destUnzipFileDir := "./unzip_file_test_dir"
	destUnzipBytesDir := "./unzip_bytes_test_dir"

	err := ZipDir(testDirRelativePath, zipFileRelativePath)
	if err != nil {
		t.Fatal(err)
	}

	defer func() {
		err := os.RemoveAll(zipFileRelativePath)
		if err != nil {
			t.Fatal(err)
		}
	}()

	err = UnzipFile(zipFileRelativePath, destUnzipFileDir)
	if err != nil {
		t.Fatal(err)
	}

	defer func() {
		err := os.RemoveAll(destUnzipFileDir)
		if err != nil {
			t.Fatal(err)
		}
	}()

	checkTestDir(t, filepath.Join(destUnzipFileDir, "test_dir"))

	fileBytes, err := os.ReadFile(zipFileRelativePath)
	if err != nil {
		t.Fatal(err)
	}

	err = UnzipBytes(fileBytes, destUnzipBytesDir)
	if err != nil {
		t.Fatal(err)
	}

	checkTestDir(t, filepath.Join(destUnzipBytesDir, "test_dir"))
}

func checkTestDir(t *testing.T, dirPath string) {
	filePaths, err := GetDirFiles(dirPath)
	if err != nil {
		t.Fatal(err)
	}

	if len(filePaths) != 2 {
		t.Fatal("文件数量不正确")
	}

	for _, filePath := range filePaths {
		if filePath != filepath.Join(dirPath, "test.txt") && filePath != filepath.Join(dirPath, "test_sub_dir/test_sub.txt") {
			t.Fatal("出现不存在的文件")
		}
	}
}