package server

import (
	"context"
	"html/template"
	"net/http"

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

// GraphView is de commitgrafiek op de project-overzichtspagina.
type GraphView struct {
	Rows          []gitgraph.Row
	Lanes         int
	Width, Height int
	SVG           template.HTML
}

func (s *Server) graphs() *gitgraph.Cache {
	s.graphOnce.Do(func() {
		s.graphCache = gitgraph.NewCache(gitgraph.DefaultMaxBytes)
	})
	return s.graphCache
}

func (s *Server) fillGraph(r *http.Request, v *View, repo store.Repo) {
	g, err := s.repoGraph(r.Context(), repo)
	if err != nil || g == nil || len(g.Rows) == 0 {
		return
	}
	v.Graph = presentGraph(r.Context(), s, repo.ID, g, i18n.Parse(v.Lang))
}

func (s *Server) repoGraph(ctx context.Context, repo store.Repo) (*gitgraph.Graph, error) {
	def := repo.DefaultBranch
	// Sleutel op repo + hoofdbranch + limiet. De tip-stand zit niet in de
	// lookup: die zou bij elke pageview git- of schijf-I/O vragen. Bij een
	// push wist refsChanged de entry (Drop) en vult refreshCache hem opnieuw.
	key := gitgraph.Key(repo.ID, nil, def, gitgraph.DefaultLimit)
	return s.graphs().Get(ctx, key, def, func(ctx context.Context) ([]gitgraph.Commit, []gitgraph.Ref, error) {
		return gitrepo.GraphHistory(ctx, s.Git, s.gdir(repo), gitgraph.DefaultLimit)
	})
}

func presentGraph(ctx context.Context, s *Server, repoID int64, g *gitgraph.Graph, lang i18n.Lang) *GraphView {
	rows := make([]gitgraph.Row, len(g.Rows))
	copy(rows, g.Rows)
	if s != nil {
		in := make([]gitrepo.Commit, 0, len(rows))
		for _, r := range rows {
			in = append(in, gitrepo.Commit{
				SHA: r.SHA, Short: r.Short, Author: r.Author, Email: r.Email,
				Unix: r.Unix, Subject: r.Subject,
			})
		}
		people := s.presentCommits(ctx, repoID, in, lang)
		for i := range rows {
			if i >= len(people) {
				break
			}
			p := people[i]
			rows[i].Avatar = p.Avatar
			rows[i].Initial = p.Initial
			rows[i].UserURL = p.UserURL
			if rows[i].Initial == "" {
				rows[i].Initial = initialOf(rows[i].Author)
			}
		}
	}
	for i := range rows {
		if rows[i].Initial == "" {
			rows[i].Initial = initialOf(rows[i].Author)
		}
	}
	return &GraphView{
		Rows:   rows,
		Lanes:  g.Lanes,
		Width:  g.Width,
		Height: g.Height,
		SVG:    template.HTML(g.SVG()),
	}
}

func (s *Server) dropGraph(repo store.Repo) {
	if s == nil {
		return
	}
	s.graphs().Drop(repo.ID)
}
