package engine

import (
	"fmt"
	"net/http"

	"github.com/deranjer/gvc/common"
	serverconfig "github.com/deranjer/gvc/server/serverconfig"
	"github.com/deranjer/store"
	"github.com/labstack/echo"
)

// GetInfo return the relevant repo specific info to the client
func (Server *GVCServer) GetInfo(context echo.Context) error {
	repo := context.Param("repo")
	config := Server.Config
	var repoInfo RepoInfoRequest // Create an engine struct that contains basic server info as well as all repo info
	for _, knownRepo := range config.Repos {
		if knownRepo.RepoName == repo {
			repoInfo.BindIP = config.BindIP
			repoInfo.Port = config.Port
			repoInfo.RawPort = config.RawPort
			repoInfo.Version = config.Version
			repoInfo.Repo = knownRepo
			for i := range repoInfo.Repo.KnownClients { // Blank out the client keys
				repoInfo.Repo.KnownClients[i].Key = "REDACTED"
			}
		}
	}
	if repoInfo.Repo.RepoName == "" {
		return echo.NewHTTPError(http.StatusNotFound, "repo apparently not found")
	}
	Server.Echo.Logger.Infof("returning information about repo: %s", repo)
	return context.JSONPretty(http.StatusAccepted, repoInfo, " ")
}

// LockFile just locks the file/folder/wildcard
func (Server *GVCServer) LockFile(context echo.Context) error {
	fileType := context.Param("type")
	fileName := context.Param("name")
	repoName := context.Param("repo")
	Server.Echo.Logger.Infof("Lockfile: %s %s %s", repoName, fileType, fileName)
	var locked common.FileTypes
	var index int
	for i, repo := range Server.Config.Repos {
		if repo.RepoName == repoName {
			index = i
			locked = Server.Config.Repos[i].Locked
		}
	}
	err := common.CheckFileTypes(fileName, fileType, locked) // making sure fi/f/wc is not already locked or cannot be locked.
	if err != nil {
		return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed checking file lock: %s", err))
	}
	switch fileType {
	case "file":
		fmt.Println("Filename: ", fileName)
		locked.Files = append(locked.Files, fileName)
	case "folder":
		fmt.Println("Folder: ", fileName)
		locked.Folders = append(locked.Folders, fileName)
	case "wildcard":
		fmt.Println("Wildcard: ", fileName)
		locked.Exts = append(locked.Exts, fileName)
	}
	Server.Config.Repos[index].Locked = locked
	Server.Echo.Logger.Infof("server attempting to lock file: %s of type %s", fileName, fileType)
	err = store.Save(serverconfig.DefaultConfigPath, Server.Config) // Save our new default config back to TOML so it can be read in
	if err != nil {
		return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("server unable to save lock to server: %s", err))
	}
	return context.String(http.StatusAccepted, "file locked on server")
}

// Refresh sends all updated information to client (like git fetch)
func (Server *GVCServer) Refresh(context echo.Context) error {
	repoName := context.Param("repo")
	var serverRepo serverconfig.RepoConfig
	for i, repo := range Server.Config.Repos {
		if repo.RepoName == repoName {
			serverRepo = Server.Config.Repos[i]
		}
	}
	// pull the locks and ignores to send back to client
	branches := serverRepo.LocalBranches
	serverLocks := serverRepo.Locked
	serverIgnores := serverRepo.DefaultIgnores
	serverNoCompress := serverRepo.NoCompress
	refreshResult := common.RepoRefreshRequest{
		Branches:   branches,
		Locked:     serverLocks,
		Ignores:    serverIgnores,
		NoCompress: serverNoCompress,
	}
	return context.JSON(http.StatusOK, refreshResult)
}

// Revert fetches the supplied file (or entire repo) at version X and pushes it to the client // TODO: This should perhaps just be part of PULL?
func (Server *GVCServer) Revert(context echo.Context) error {
	repoName := context.Param("repo")
	return context.JSON(http.StatusOK, repoName)
}

// Pull fetches the latest changes from the server to the client.
func (Server *GVCServer) Pull(context echo.Context) error {
	helloMsg := "server alive"
	return context.JSON(http.StatusOK, helloMsg)
}

// Hello just verifies the server is running //TODO remove this, just extra shit we are sending
func (Server *GVCServer) Hello(context echo.Context) error {
	helloMsg := "server alive"
	return context.JSON(http.StatusOK, helloMsg)
}
