package clientcmd

import (
	"fmt"

	clientconfig "github.com/deranjer/gvc/client/clientconfig"
	"github.com/deranjer/gvc/common"
	"github.com/go-resty/resty/v2"
)

//LockFiles locks file(s)/folder based on name/wildcard, etc
func LockFiles(input string, inputType string, conf *clientconfig.Gvcconfig) 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
	}
	locked := conf.Locked
	connectionString, err := FindServer("", conf.CurrentBranch, conf) //TODO: Maybe allow user to specify lock server? Seems like they should just use the default server though
	switch inputType {                                                // TODO: add default case for generic error handling // TODO: there is no user supplied input here, so WHY?
	case "file":
		err := common.CheckFileTypes(input, "file", locked)
		if err != nil {
			return fmt.Errorf("%s already locked: %s", input, err)
		}
		fmt.Println("Adding file to locked: ", input)
		conf.Locked.Files = append(conf.Locked.Files, input)
		err = SendLockToServer(connectionString, conf.RepoName, "file", input)
		if err != nil {
			return fmt.Errorf("error sending lock to server: %s", err)
		}
		return nil
	case "folder":
		err := common.CheckFileTypes(input, "folder", locked)
		if err != nil {
			return fmt.Errorf("%s is already locked: %s", input, err)
		}
		fmt.Println("Adding folder to locked: ", input)
		conf.Locked.Folders = append(conf.Locked.Folders, input)
		err = SendLockToServer(connectionString, conf.RepoName, "folder", input)
		if err != nil {
			return fmt.Errorf("error sending lock to server: %s", err)
		}
		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
		}
		err := common.CheckFileTypes(wildcard, "wildcard", locked)
		if err != nil {
			return fmt.Errorf("%s is already locked: %s", input, err)
		}
		fmt.Println("Adding wildcard to locked: ", wildcard)
		conf.Locked.Exts = append(conf.Locked.Exts, wildcard)
		err = SendLockToServer(connectionString, conf.RepoName, "wildcard", input)
		if err != nil {
			return fmt.Errorf("error sending lock to server: %s", err)
		}
		return nil
	}
	return fmt.Errorf("This... should not have happened, some kind of internal error on LockFiles function call, switch failure")
}

// RemoveLockFiles removes files/folders/wildcards from the locked list
func RemoveLockFiles(input string, inputType string, conf *clientconfig.Gvcconfig) 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
	}
	locked := conf.Locked
	switch inputType { // TODO: add default case for generic error handling
	case "file":
		err := common.CheckFileTypes(input, "file", locked)
		if err != nil {
			fmt.Println("Removing file from locked: ", input)
			for i, fileLock := range locked.Files {
				if input == fileLock {
					conf.Locked.Files[i] = conf.Locked.Files[len(conf.Locked.Files)-1] // Deleting the element
					conf.Locked.Files = conf.Locked.Files[:len(conf.Locked.Files)-1]   // redoing the slice
					fmt.Println("Removing file from locked: ", input)
					return nil
				}
			}
		}
		fmt.Println("File not found in ingores, unable to remove: ", input)
		return nil
	case "folder":
		err := common.CheckFileTypes(input, "folder", locked)
		if err != nil {
			for i, folderLock := range locked.Folders {
				if input == folderLock {
					conf.Locked.Folders[i] = conf.Locked.Folders[len(conf.Locked.Folders)-1]
					conf.Locked.Folders = conf.Locked.Files[:len(conf.Locked.Folders)-1]
					fmt.Println("Removing folder from locked: ", input)
					return nil
				}
			}
		}
		fmt.Println("Folder not found in ingores, unable to remove: ", input)
		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
		}
		err := common.CheckFileTypes(wildcard, "wildcard", locked)
		if err != nil {
			for i, wildcardLock := range locked.Exts {
				if input == wildcardLock {
					conf.Locked.Exts[i] = conf.Locked.Exts[len(conf.Locked.Exts)-1]
					conf.Locked.Exts = conf.Locked.Exts[:len(conf.Locked.Exts)-1]
					fmt.Println("Removing wildcard from locked: ", wildcard)
					return nil
				}
			}
		}
		fmt.Println("Wildcard not found in ingores, unable to remove: ", wildcard)
		return nil
	}
	return fmt.Errorf("This... should not have happened, some kind of internal error on RemoveLockFiles function call, switch failure")
}

// SendLockToServer sends an updated lock file to the server
func SendLockToServer(connectionString string, repoName string, fileType string, fileName string) error {
	client := resty.New()
	resp, err := client.R().
		SetPathParams(map[string]string{
			"repoName": repoName,
			"type":     fileType,
			"name":     fileName,
		}).
		Get(connectionString + "/lock/" + "{repoName}/" + "{type}/" + "{name}") //creating the full string to get info
	if err != nil {
		return fmt.Errorf("error connecting to server at: %s: error was: %s", connectionString, err)
	}
	if resp.IsError() {
		if resp.StatusCode() == 404 {
			return fmt.Errorf("error: repo was not found on server, 404: %s", resp.Request.URL)
		}
		return fmt.Errorf("%s: response code: %d: %s", resp.Request.URL, resp.StatusCode(), resp)
	}
	fmt.Println(resp)
	return nil
}
