package sync

import (
	"path/filepath"
	"reflect"
	"testing"

	"git.csclub.uwaterloo.ca/public/merlin/config"
	"git.csclub.uwaterloo.ca/public/merlin/logger"
)

func dummyRepoConf(name string, syncType string, frequencyStr string, localDir string, rsyncHost string, rsyncDir string) *config.Repo {
	doneChan := make(chan config.SyncResult)
	stopChan := make(chan struct{})

	repoLogFile := filepath.Join("test_files", name, name+".log")
	logger := logger.NewLogger(name, repoLogFile, false)

	return &config.Repo{
		Name:           name,
		SyncType:       syncType,
		FrequencyStr:   frequencyStr,
		Frequency:      0,
		MaxTime:        config.DEFAULT_MAX_TIME,
		LocalDir:       localDir,
		RsyncHost:      rsyncHost,
		RsyncDir:       rsyncDir,
		RsyncUser:      "",
		PasswordFile:   "",
		StateFile:      "",
		RepoLogFile:    repoLogFile,
		Logger:         logger,
		RsyncLogFile:   "/tmp/log/" + name + "-rsync.log",
		ZfssyncLogFile: "",
		DoneChan:       doneChan,
		StopChan:       stopChan,
		State: &config.RepoState{
			IsRunning:            false,
			LastAttemptStartTime: 0,
			LastAttemptRunTime:   0,
			LastAttemptExit:      config.NOT_RUN_YET,
		},
	}
}

func TestGetSyncCommand(t *testing.T) {

	config.Conf.DownloadDir = "test_files"
	config.Conf.IPv4Address = "0.0.0.0"
	config.Conf.DownloadDir = "/tmp/mirror"

	testData := []struct {
		repoConf *config.Repo
		expected []string
	}{
		{
			repoConf: dummyRepoConf("ubuntu-releases", "csc-sync-standard", "bi-hourly", "ubuntu-releases", "rsync.releases.ubuntu.com", "releases"),
			expected: []string{
				"nice", "rsync", "-aH", "--no-owner", "--no-group", "--delete-after",
				"--delay-updates", "--safe-links", "--timeout=3600", "-4", "--address=0.0.0.0",
				"--exclude", ".~tmp~/", "--quiet", "--stats", "--log-file=/tmp/log/ubuntu-releases-rsync.log",
				"rsync://rsync.releases.ubuntu.com/releases", "/tmp/mirror/ubuntu-releases",
			},
		},
		{
			repoConf: dummyRepoConf("raspberrypi", "csc-sync-standard-ipv6", "bi-hourly", "raspberrypi", "apt-repo.raspberrypi.org", "archive"),
			expected: []string{
				"nice", "rsync", "-aH", "--no-owner", "--no-group", "--delete-after",
				"--delay-updates", "--safe-links", "--timeout=3600", "-6", "--address=0.0.0.0",
				"--exclude", ".~tmp~/", "--quiet", "--stats", "--log-file=/tmp/log/raspberrypi-rsync.log",
				"apt-repo.raspberrypi.org::archive", "/tmp/mirror/raspberrypi",
			},
		},
	}

	for _, test := range testData {

		syncCommand := getSyncCommand(test.repoConf)

		// check for correct command output
		if !reflect.DeepEqual(syncCommand, test.expected) {
			t.Errorf("Invalid command string for %s repo\nRECIEVED:\n%+v\nEXPECTED:\n%+v\n", test.repoConf.Name, syncCommand, test.expected)
		}

		// check if download dir was created

	}
}
