package clientcmd

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

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

// ConfigPath is the global path to the config that is injected from the main client package.
var ConfigPath string

func validateFileType(path string, inputType string) error {
	if inputType == "wildcard" { // Can't stat wildcard type
		return nil
	}
	fullPath, err := filepath.Abs(path)
	if err != nil {
		return fmt.Errorf("cannot stat file, invalid input? %s", err)
	}
	fileInfo, err := os.Stat(fullPath)
	if err != nil {
		return fmt.Errorf("unable to read file, corrupted? %s", err)
	}
	if fileInfo.IsDir() {
		if inputType == "folder" || inputType == "all" {
			return nil
		} else {
			return fmt.Errorf("folder flag was used, but input is not a folder, will not continue")
		}
	}
	return nil
}

// FindServer finds the supplied server connection settings, creates a connection string and returns it
func FindServer(serverName string, branchName string, conf *clientconfig.Gvcconfig) (connectionString string, err error) {
	if branchName == "" { // If no branch listed select master TODO: in future the 'default' branch will be their current branch
		branchName = "master"
	}
	if serverName == "" { // if no serverName is specified, just use the default
		for _, remote := range conf.Remotes {
			if remote.Default {
				serverName = remote.Name
			}
		}
	}
	for _, remote := range conf.Remotes {
		if serverName == remote.Name {
			fmt.Printf("Server found in config, connecting to: %s, host: %s, port: %d \n", remote.Name, remote.Host, remote.Port)
			port := ":" + strconv.Itoa(remote.Port)
			connectionString := "http://" + remote.Host + port //Create our connection string //'http://server:port'
			fmt.Println("Generated connection string: ", connectionString)
			return connectionString, nil
		}
	}
	return "", fmt.Errorf("unable to find server name in config")
}
