package clientcmd

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

	clientconfig "github.com/deranjer/gvc/client/clientconfig"
	"github.com/deranjer/gvc/common"
	"github.com/deranjer/gvc/common/engine"
)

//AddFiles adds files to the repo, inputType specifies file, folder, wildcard or all
func AddFiles(input string, inputType string, ignore common.FileTypes, m *engine.Manager) error {
	err := validateFileType(input, inputType) // Making sure that if the file flag was used a folder was not supplied and vice versa
	if err != nil {
		return err
	}
	workingDir, err := os.Getwd()
	if err != nil {
		return err
	}
	var trackedFiles []string
	switch inputType {
	case "file": // If the -file flag was used, then make sure it is a file, make sure not on ignore list, then add it to tracked files
		_, err := os.Stat(input)
		if err != nil {
			return fmt.Errorf("unable to add file %s", err)
		}
		err = common.CheckFileTypes(input, "file", ignore)
		if err != nil {
			return fmt.Errorf("unable to add file as it (or ext) is on the ignores list %s", input)
		}
		// absolute := filepath.IsAbs(input)
		// if absolute {
		// 	relativePath, err := filepath.Rel(workingDir, input)
		// 	if err != nil {
		// 		return fmt.Errorf("unable to create relative path for file: %s", err)
		// 	}
		// }
		relativePath := input //TODO: Figure out if path is corrrect?
		relativePath = "test.go"
		fmt.Println("Relative Path: ", relativePath)
		err = m.AddFileToRepo(relativePath)
		if err != nil {
			return fmt.Errorf("unable to add file to repo: %s", err)
		}
		trackedFiles = append(trackedFiles, relativePath)
		fmt.Println("adding file: ", relativePath)
	case "folder":
		folder, err := os.Stat(input)
		if err != nil {
			return fmt.Errorf("unable to add folder %s", err)
		}
		if !folder.IsDir() {
			return fmt.Errorf("file exists, but is not a folder %s", err)
		}
		filepath.Walk(input, func(path string, info os.FileInfo, err error) error {
			if err != nil {
				return fmt.Errorf("failure accessing path %s", err)
			}
			if info.IsDir() {
				if info.Name() == ".gvc" { // can't track anything in .gvc
					fmt.Println("skipping .gvc directory")
					m.Info().Msg("skipping .gvc directory")
					return filepath.SkipDir
				}
				err = common.CheckFileTypes(info.Name(), "folder", ignore)
				if err != nil {
					fmt.Printf("skipping ignored directory: %s\n", err)
					m.Info().Msgf("skipping ignored directory: %s\n", err)
					return filepath.SkipDir
				}
			} else {
				err = common.CheckFileTypes(info.Name(), "file", ignore)
				if err != nil {
					fmt.Printf("Not adding file %s as it is on the ingores list \n", info.Name())
					return nil
				}
			}
			fmt.Println("adding file: ", path)
			relativePath, err := filepath.Rel(workingDir, path)
			if err != nil {
				return fmt.Errorf("unable to create relative path for file: %s", err)
			}
			err = m.AddFileToRepo(relativePath)
			if err != nil {
				return fmt.Errorf("unable to add file to repo: %s", err)
			}
			trackedFiles = append(trackedFiles, relativePath)
			return nil
		})
	case "wildcard":
		var wildcard string
		if input[:1] == "*" { // Removing the wildcard char since we don't store that or test with that char
			wildcard = input[1:]
		} else {
			wildcard = input
		}
		m.Info().Msgf("Adding all files with wildcard: %s", wildcard)
		err := common.CheckFileTypes(wildcard, "wildcard", ignore)
		if err != nil {
			return err
		}
		filepath.Walk(workingDir, func(path string, info os.FileInfo, err error) error {
			fmt.Println("path: ", path)
			fmt.Printf("Checking file: %s\n", info.Name())
			if err != nil {
				return fmt.Errorf("failure accessing path %s", err)
			}
			if info.IsDir() {
				if info.Name() == ".gvc" { // can't track anything in .gvc
					fmt.Println("skipping .gvc directory")
					m.Info().Msg("skipping .gvc directory")
					return filepath.SkipDir
				}
				err = common.CheckFileTypes(info.Name(), "folder", ignore)
				if err != nil {
					fmt.Printf("skipping ignored directory: %s\n", err)
					m.Info().Msgf("skipping ignored directory: %s\n", err)
					return filepath.SkipDir
				}
			} else {
				err = common.CheckFileTypes(info.Name(), "file", ignore)
				if err != nil {
					fmt.Printf("Not adding file %s as it is on the ingores list \n", info.Name())
					return nil
				}
			}
			fileExt := filepath.Ext(path)
			if fileExt == wildcard { // seeing if the file ext matches the wildcard
				fmt.Println("Adding file that matched wildcard: ", info.Name())
				relativePath, err := filepath.Rel(workingDir, path)
				if err != nil {
					fmt.Printf("unable to create relative path for file: %s\n", err)
					m.Info().Msgf("unable to create relative path for file: %s\n", err)
					return nil
				}
				err = m.AddFileToRepo(relativePath)
				if err != nil {
					fmt.Printf("unable to add file to repo: %s\n", err)
					m.Info().Msgf("unable to add file to repo: %s\n", err)
					return nil
				}
				trackedFiles = append(trackedFiles, relativePath)
			}
			return nil
		})
	case "all":
		m.Info().Msg("Adding all files...")
		filepath.Walk(workingDir, func(path string, info os.FileInfo, err error) error {
			if err != nil {
				fmt.Println("Err accessing path: ", err)
				return fmt.Errorf("failure accessing path %s", err)
			}
			if info.IsDir() {
				if info.Name() == ".gvc" { // can't track anything in .gvc
					fmt.Println("skipping .gvc directory")
					m.Info().Msg("skipping .gvc directory")
					return filepath.SkipDir
				}
				err = common.CheckFileTypes(info.Name(), "folder", ignore)
				if err != nil {
					fmt.Printf("skipping ignored directory: %s\n", err)
					m.Info().Msgf("skipping ignored directory: %s\n", err)
					return filepath.SkipDir
				}
			} else {
				err = common.CheckFileTypes(info.Name(), "file", ignore)
				if err != nil {
					fmt.Printf("Not adding file %s as it is on the ingores list \n", info.Name())
					return nil
				}
			}
			relativePath, err := filepath.Rel(workingDir, path)
			if err != nil {
				return fmt.Errorf("unable to create relative path for file: %s", err)
			}
			if relativePath == "." { //Ignoring current directory
				return nil
			}
			fmt.Println("Adding file to repo: ", path)
			m.Info().Msgf("Adding file to repo: %s", path)
			err = m.AddFileToRepo(relativePath)
			if err != nil {
				fmt.Printf("unable to add file to repo: %s\n", err)
				return nil
			}
			trackedFiles = append(trackedFiles, relativePath)
			return nil
		})
	}
	if len(trackedFiles) > 0 {
		fmt.Println("Added tracked files", trackedFiles) // Print out all the new tracked files
		m.Info().Msgf("Adding the following files to tracked: %s", trackedFiles)
	} else {
		fmt.Println("No files found that could be added to tracked")
		m.Info().Msg("No files found that could be added to tracked")
	}
	return nil
}

// checkRemotesSlice just ranges through the remotes looking for duplicates
func checkRemotesSlice(name, host string, port int, remotes []clientconfig.Remote) error {
	for _, remote := range remotes { // Names of remotes must be unique so make sure they are
		if name == remote.Name {
			return fmt.Errorf("remote with that name already exits: %s", name)
		}
	}
	for _, remote := range remotes { // make sure we don't have another remote with same host and port
		if host == remote.Host && port == remote.Port {
			return fmt.Errorf("remote with that host and port config already exists: %s:%d", host, port)
		}
	}
	return nil
}
