package server

import (
	"net/http"
	"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/store"
)

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"
	dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
	tips, _ := gitrepo.BranchTips(r.Context(), s.Git, dir)
	patterns, _ := s.Store.ProtectedPatterns(r.Context(), repo.ID)
	lang := s.langOf(r)
	for _, tip := range tips {
		when, title := branchWhen(lang, tip.Date)
		row := BranchRow{
			Name: tip.Name, SHA: tip.SHA, Short: shortSHA(tip.SHA),
			Subject: tip.Subject, When: when, WhenTitle: title,
			Protected: access.BranchProtected(patterns, tip.Name),
			Default:   tip.Name == repo.DefaultBranch,
		}
		if !row.Default && repo.DefaultBranch != "" {
			ahead, behind, err := gitrepo.AheadBehind(r.Context(), s.Git, dir, 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
		}
		return v.Branches[i].Name < v.Branches[j].Name
	})
	tags, _ := gitrepo.Tags(r.Context(), s.Git, dir)
	for _, name := range tags {
		v.Tags = append(v.Tags, TagRow{Name: name})
	}
	s.render(w, "branches", v)
}

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 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.ShortAgo(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, ""
}
