package server

import (
	"net/http"
	"net/url"
	"sort"
	"strconv"
	"strings"
	"time"

	"gitlab.com/Timfa/bluegit/internal/access"
	"gitlab.com/Timfa/bluegit/internal/gitrepo"
	"gitlab.com/Timfa/bluegit/internal/i18n"
	"gitlab.com/Timfa/bluegit/internal/names"
	"gitlab.com/Timfa/bluegit/internal/store"
)

// Een branch zonder commit in drie maanden is inactief, zoals bij GitLab.
const branchStaleAfter = 90 * 24 * time.Hour

func (s *Server) branches(w http.ResponseWriter, r *http.Request) {
	_, repo, role, ok := s.guard(w, r, access.RoleReadonly)
	if !ok {
		return
	}
	s.absorbMergedMRs(r.Context(), repo)
	v := s.repoView(w, r, repo, role, "title.branches")
	v.Page = "branches"
	v.Wide = true
	tips, _ := s.cBranchTips(r.Context(), repo)
	patterns, _ := s.Store.ProtectedPatterns(r.Context(), repo.ID)
	lang := s.langOf(r)
	now := time.Now()
	for _, tip := range tips {
		when, title := branchWhen(lang, tip.Date)
		unix, _ := strconv.ParseInt(strings.TrimSpace(tip.Date), 10, 64)
		row := BranchRow{
			Name: tip.Name, SHA: tip.SHA, Short: shortSHA(tip.SHA),
			Subject: tip.Subject, When: when, WhenTitle: title, Unix: unix,
			Protected: access.BranchProtected(patterns, tip.Name),
			Default:   tip.Name == repo.DefaultBranch,
			RepoPath:  repo.FullPath(),
			Target:    repo.DefaultBranch,
			ZipURL:    branchArchiveURL(repo, tip.Name, "zip"),
			TarURL:    branchArchiveURL(repo, tip.Name, "tar.gz"),
		}
		row.CanEdit = role.CanWriteCode() && !row.Default && !row.Protected
		if !row.Default && repo.DefaultBranch != "" {
			ahead, behind, err := s.cAheadBehind(r.Context(), repo, repo.DefaultBranch, tip.Name)
			if err == nil {
				row.Ahead, row.Behind = ahead, behind
			}
		}
		if p, err := s.Store.LatestPipelineByCommit(r.Context(), repo.ID, tip.SHA); err == nil {
			jobs, _ := s.Store.JobsByPipeline(r.Context(), p.ID)
			row.PipeID = p.ID
			row.PipeStatus = displayStatus(p.Status, jobs)
			row.PipeLabel = s.tr(r, "pipe."+row.PipeStatus)
		}
		if mrs, err := s.Store.OpenMergeRequestsBySource(r.Context(), repo.ID, tip.Name); err == nil {
			for _, mr := range mrs {
				row.OpenMRs = append(row.OpenMRs, mr.Number)
			}
		}
		v.Branches = append(v.Branches, row)
	}
	sort.Slice(v.Branches, func(i, j int) bool {
		if v.Branches[i].Default != v.Branches[j].Default {
			return v.Branches[i].Default
		}
		if v.Branches[i].Unix != v.Branches[j].Unix {
			return v.Branches[i].Unix > v.Branches[j].Unix
		}
		return v.Branches[i].Name < v.Branches[j].Name
	})
	state := branchTab(r.URL.Query().Get("state"))
	board := &BranchBoard{State: state}
	for _, row := range v.Branches {
		if branchIsStale(row.Unix, row.Default, now) {
			board.Stale = append(board.Stale, row)
		} else {
			board.Active = append(board.Active, row)
		}
	}
	switch state {
	case "active":
		board.ShowActive = true
	case "stale":
		board.ShowStale = true
	case "all":
		board.ShowActive, board.ShowStale = true, true
	default:
		board.ShowActive = len(board.Active) > 0 || len(board.Stale) == 0
		board.ShowStale = len(board.Stale) > 0
	}
	v.Branch = board
	tags, _ := s.cTags(r.Context(), repo)
	for _, name := range tags {
		v.Tags = append(v.Tags, TagRow{Name: name})
	}
	s.render(w, "branches", v)
}

func (s *Server) branchArchive(w http.ResponseWriter, r *http.Request) {
	_, repo, _, ok := s.guard(w, r, access.RoleReadonly)
	if !ok {
		return
	}
	name := r.URL.Query().Get("name")
	format := r.URL.Query().Get("format")
	if names.ValidBranch(name) != nil || (format != "zip" && format != "tar.gz") {
		http.NotFound(w, r)
		return
	}
	dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
	if gitOne(r.Context(), s.Git, dir, "rev-parse", "--verify", "--quiet", "refs/heads/"+name) == "" {
		http.NotFound(w, r)
		return
	}
	s.writeArchive(w, r, repo, dir, "refs/heads/"+name, name, format)
}

func (s *Server) createBranch(w http.ResponseWriter, r *http.Request) {
	u, repo, _, ok := s.guard(w, r, access.RoleDeveloper)
	if !ok || !s.csrfOK(w, r) {
		return
	}
	back := repoURL(repo) + "/-/branches"
	if !s.uiOK(w, r, back, s.opCreateBranch(r.Context(), u, repo, r.FormValue("name"), r.FormValue("from"))) {
		return
	}
	s.redirect(w, r, back, s.tr(r, "flash.branchCreated"), "")
}

func (s *Server) deleteBranch(w http.ResponseWriter, r *http.Request) {
	u, repo, _, ok := s.guard(w, r, access.RoleDeveloper)
	if !ok || !s.csrfOK(w, r) {
		return
	}
	back := repoURL(repo) + "/-/branches"
	if !s.uiOK(w, r, back, s.opDeleteBranch(r.Context(), u, repo, r.FormValue("name"), r.FormValue("confirm"))) {
		return
	}
	s.redirect(w, r, back, s.tr(r, "flash.branchDeleted"), "")
}

func (s *Server) renameBranch(w http.ResponseWriter, r *http.Request) {
	u, repo, _, ok := s.guard(w, r, access.RoleDeveloper)
	if !ok || !s.csrfOK(w, r) {
		return
	}
	back := repoURL(repo) + "/-/branches"
	if !s.uiOK(w, r, back, s.opRenameBranch(r.Context(), u, repo, r.FormValue("name"), r.FormValue("new_name"), r.FormValue("confirm"))) {
		return
	}
	s.redirect(w, r, back, s.tr(r, "flash.branchRenamed"), "")
}

func branchTab(raw string) string {
	switch raw {
	case "active", "stale", "all":
		return raw
	default:
		return "overview"
	}
}

func branchIsStale(unix int64, isDefault bool, now time.Time) bool {
	if isDefault || unix <= 0 {
		return false
	}
	return now.Sub(time.Unix(unix, 0)) > branchStaleAfter
}

func branchArchiveURL(repo interface{ FullPath() string }, name, format string) string {
	return "/" + repo.FullPath() + "/-/branches/archive?name=" + url.QueryEscape(name) + "&format=" + format
}

func branchWhen(lang i18n.Lang, unixText string) (short, title string) {
	unix, err := strconv.ParseInt(strings.TrimSpace(unixText), 10, 64)
	if err != nil || unix <= 0 {
		return "", ""
	}
	at := time.Unix(unix, 0).UTC()
	return i18n.Ago(lang, unix), at.Format("2006-01-02 15:04 UTC")
}

// branchLocked weigert de standaardbranch en elke beschermde branch, ook voor een beheerder.
func (s *Server) branchLocked(r *http.Request, repo store.Repo, name string) (bool, string) {
	if name == repo.DefaultBranch {
		return true, s.tr(r, "err.branchLocked", name)
	}
	patterns, _ := s.Store.ProtectedPatterns(r.Context(), repo.ID)
	if access.BranchProtected(patterns, name) {
		return true, s.tr(r, "err.branchLocked", name)
	}
	return false, ""
}
