package git

import (
	"fmt"
	"gitea-page/internal/config"
	"github.com/go-git/go-git/v5"
	"github.com/go-git/go-git/v5/plumbing"
	"github.com/go-git/go-git/v5/plumbing/transport/ssh"
	"github.com/pkg/errors"
	"github.com/rs/zerolog/log"
	cssh "golang.org/x/crypto/ssh"
	"os"
)

type GitHandler struct {
	Config config.GiteaPagesConfig
}

func (g GitHandler) GetRepository(name, owner, url string) {
	log.Debug().Msg("Try to Get Repository")
	path := fmt.Sprintf("%s/%s/%s", g.Config.RootPath, owner, name)
	log.Debug().Str("path", path).Msg("Get Path")
	_, err := os.Stat(path)
	if os.IsNotExist(err) {
		g.clone(name, owner, url, path)
	} else {
		g.pull(name, owner, url, path)
	}

}

func (g GitHandler) pull(name, owner, url, path string) {
	log.Debug().Msg("Dont pull, delete and clone again")
	e := os.RemoveAll(path)
	if e != nil {
		log.Fatal().Err(e).Msg("Cant remove folder")
	}

	g.clone(name, owner, url, path)
	return
	log.Debug().Msg("Try to Pull")
	publicKeyAuth, err := ssh.NewPublicKeysFromFile("git", g.Config.PublicKey.Filename, "")
	if err != nil {
		log.Error().Err(err).Str("filename", g.Config.PublicKey.Filename).Msg("Cant parse Public key")
		return
	}
	publicKeyAuth.HostKeyCallbackHelper = ssh.HostKeyCallbackHelper{
		HostKeyCallback: cssh.InsecureIgnoreHostKey(),
	}

	r,_ := git.PlainOpen(path)
	w,_ := r.Worktree()
	err = w.Pull(&git.PullOptions{RemoteName: "origin", Auth: publicKeyAuth, Depth: 1})
	if err != nil {
		if errors.Is(err, git.NoErrAlreadyUpToDate) {
			log.Debug().Msg("Already up to date")
		} else {
			log.Error().Err(err).Msg("Error doing pull")
		}

	}
}
func (g GitHandler) clone(name, owner, url, path string) {
	log.Debug().Msg("Try to Clone")

	publicKeyAuth, err := ssh.NewPublicKeysFromFile("git", g.Config.PublicKey.Filename, "")
	if err != nil {
		log.Error().Err(err).Str("filename", g.Config.PublicKey.Filename).Msg("Cant parse Public key")
		return
	}
	publicKeyAuth.HostKeyCallbackHelper = ssh.HostKeyCallbackHelper{
		HostKeyCallback: cssh.InsecureIgnoreHostKey(),
	}

	var remoteBranch plumbing.ReferenceName
	remoteBranch = plumbing.ReferenceName(g.Config.Branch)

	_, err = git.PlainClone(path, false, &git.CloneOptions{
		URL:      url,
		Progress: os.Stdout,
		Auth: publicKeyAuth,
		Depth: 1,
		ReferenceName: remoteBranch,
	})

	if err != nil {
		log.Err(err).Str("url", url).Str("publickey", publicKeyAuth.String()).Msg("Cant clone repository")
	}
}