package convert

import (
	repo_model "code.gitea.io/gitea/models/repo"
	user_model "code.gitea.io/gitea/models/user"
	"code.gitea.io/gitea/modules/convert"
	"code.gitea.io/gitea/modules/git"
	api "code.gitea.io/gitea/modules/structs"
	hat_api "code.gitlink.org.cn/Gitlink/gitea_hat.git/modules/structs"
	"net/url"
	"time"
)

func ToCommit(repo *repo_model.Repository, gitRepo *git.Repository, commit *git.Commit, userCache map[string]*user_model.User, stat bool) (*hat_api.Commit, error) {
	giteaApiCommit, err := ToCommitNotDiff(repo, gitRepo, commit, userCache, stat)
	if err != nil {
		return nil, err
	}

	err = commit.LoadBranchName()
	if err != nil {
		return nil, err
	}

	return &hat_api.Commit{
		Commit: giteaApiCommit,
		Branch: commit.Branch,
	}, nil
}

func ToCommitNotDiff(repo *repo_model.Repository, gitRepo *git.Repository, commit *git.Commit, userCache map[string]*user_model.User, stat bool) (*api.Commit, error) {
	var apiAuthor, apiCommitter *api.User

	// Retrieve author and committer information

	var cacheAuthor *user_model.User
	var ok bool
	if userCache == nil {
		cacheAuthor = (*user_model.User)(nil)
		ok = false
	} else {
		cacheAuthor, ok = userCache[commit.Author.Email]
	}

	if ok {
		apiAuthor = convert.ToUser(cacheAuthor, nil)
	} else {
		author, err := user_model.GetUserByEmail(commit.Author.Email)
		if err != nil && !user_model.IsErrUserNotExist(err) {
			return nil, err
		} else if err == nil {
			apiAuthor = convert.ToUser(author, nil)
			if userCache != nil {
				userCache[commit.Author.Email] = author
			}
		}
	}

	var cacheCommitter *user_model.User
	if userCache == nil {
		cacheCommitter = (*user_model.User)(nil)
		ok = false
	} else {
		cacheCommitter, ok = userCache[commit.Committer.Email]
	}

	if ok {
		apiCommitter = convert.ToUser(cacheCommitter, nil)
	} else {
		committer, err := user_model.GetUserByEmail(commit.Committer.Email)
		if err != nil && !user_model.IsErrUserNotExist(err) {
			return nil, err
		} else if err == nil {
			apiCommitter = convert.ToUser(committer, nil)
			if userCache != nil {
				userCache[commit.Committer.Email] = committer
			}
		}
	}

	// Retrieve parent(s) of the commit
	apiParents := make([]*api.CommitMeta, commit.ParentCount())
	for i := 0; i < commit.ParentCount(); i++ {
		sha, _ := commit.ParentID(i)
		apiParents[i] = &api.CommitMeta{
			URL: repo.APIURL() + "/git/commits/" + url.PathEscape(sha.String()),
			SHA: sha.String(),
		}
	}

	res := &api.Commit{
		CommitMeta: &api.CommitMeta{
			URL:     repo.APIURL() + "/git/commits/" + url.PathEscape(commit.ID.String()),
			SHA:     commit.ID.String(),
			Created: commit.Committer.When,
		},
		HTMLURL: repo.HTMLURL() + "/commit/" + url.PathEscape(commit.ID.String()),
		RepoCommit: &api.RepoCommit{
			URL: repo.APIURL() + "/git/commits/" + url.PathEscape(commit.ID.String()),
			Author: &api.CommitUser{
				Identity: api.Identity{
					Name:  commit.Author.Name,
					Email: commit.Author.Email,
				},
				Date: commit.Author.When.Format(time.RFC3339),
			},
			Committer: &api.CommitUser{
				Identity: api.Identity{
					Name:  commit.Committer.Name,
					Email: commit.Committer.Email,
				},
				Date: commit.Committer.When.Format(time.RFC3339),
			},
			Message: commit.Message(),
			Tree: &api.CommitMeta{
				URL:     repo.APIURL() + "/git/trees/" + url.PathEscape(commit.ID.String()),
				SHA:     commit.ID.String(),
				Created: commit.Committer.When,
			},
			Verification: convert.ToVerification(commit),
		},
		Author:    apiAuthor,
		Committer: apiCommitter,
		Parents:   apiParents,
	}

	// Retrieve files affected by the commit
	if stat {
		fileStatus, err := git.GetCommitFileStatus(gitRepo.Ctx, repo.RepoPath(), commit.ID.String())
		if err != nil {
			return nil, err
		}
		affectedFileList := make([]*api.CommitAffectedFiles, 0, len(fileStatus.Added)+len(fileStatus.Removed)+len(fileStatus.Modified))
		for _, files := range [][]string{fileStatus.Added, fileStatus.Removed, fileStatus.Modified} {
			for _, filename := range files {
				affectedFileList = append(affectedFileList, &api.CommitAffectedFiles{
					Filename: filename,
				})
			}
		}

		//diff, err := gitdiff.GetDiff(gitRepo, &gitdiff.DiffOptions{
		//		AfterCommitID: commit.ID.String(),
		//})
		//if err != nil {
		//		return nil, err
		//}

		res.Files = affectedFileList
		//res.Stats = &api.CommitStats{
		//		Total:     diff.TotalAddition + diff.TotalDeletion,
		//		Additions: diff.TotalAddition,
		//		Deletions: diff.TotalDeletion,
		//}
	}

	return res, nil
}
