package server

import (
	"context"
	"net/http"
	"strings"
	"unicode/utf8"

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

func (s *Server) profile(w http.ResponseWriter, r *http.Request) {
	name := strings.ToLower(strings.TrimSpace(r.PathValue("username")))
	u, err := s.Store.UserByUsername(r.Context(), name)
	if err != nil {
		http.NotFound(w, r)
		return
	}
	v := s.view(w, r, u.Username)
	v.Profile = &u
	viewer := int64(0)
	if v.User != nil {
		viewer = v.User.ID
	}
	ids, err := s.Store.ListRepoIDs(r.Context(), viewer)
	if err != nil {
		ids = nil
	}
	v.Heat = s.heatmap(r.Context(), u.ID, ids, s.langOf(r))
	s.render(w, "profile", v)
}

func (s *Server) presentCommits(ctx context.Context, repoID int64, in []gitrepo.Commit, lang i18n.Lang) []CommitRow {
	shas := make([]string, 0, len(in))
	for _, c := range in {
		if c.SHA != "" {
			shas = append(shas, c.SHA)
		}
	}
	pushers := map[string]store.Pusher{}
	if s.Store != nil && repoID != 0 && len(shas) > 0 {
		if got, err := s.Store.PushersBySHA(ctx, repoID, shas); err == nil {
			pushers = got
		}
	}
	cache := map[string]store.User{}
	miss := map[string]bool{}
	var rows []CommitRow
	for _, c := range in {
		rows = append(rows, s.oneCommit(ctx, c, pushers[c.SHA], lang, cache, miss))
	}
	return rows
}

func (s *Server) oneCommit(ctx context.Context, c gitrepo.Commit, pusher store.Pusher, lang i18n.Lang, cache map[string]store.User, miss map[string]bool) CommitRow {
	row := CommitRow{
		SHA: c.SHA, Short: c.Short, Author: c.Author, Date: c.Date,
		Subject: c.Subject, Body: c.Body, When: i18n.Ago(lang, c.Unix),
		Initial: initialOf(c.Author),
	}
	if u, ok := s.userForEmail(ctx, c.Email, cache, miss); ok {
		row.Author = u.Username
		row.UserURL = "/users/" + u.Username
		row.Avatar = u.AvatarURL
		row.Initial = initialOf(u.Username)
		return row
	}
	if pusher.UserID != 0 && pusher.Username != "" {
		row.Author = pusher.Username
		row.UserURL = "/users/" + pusher.Username
		row.Avatar = pusher.AvatarURL
		row.Initial = initialOf(pusher.Username)
		raw := strings.TrimSpace(c.Author)
		if raw != "" && !strings.EqualFold(raw, pusher.Username) {
			row.RawName = raw
			row.PushedBy = pusher.Username
		}
	}
	return row
}

func (s *Server) userForEmail(ctx context.Context, email string, cache map[string]store.User, miss map[string]bool) (store.User, bool) {
	if s.Store == nil {
		return store.User{}, false
	}
	key := strings.ToLower(strings.TrimSpace(email))
	if u, ok := cache[key]; ok {
		return u, true
	}
	if miss[key] {
		return store.User{}, false
	}
	u, ok := s.Store.UserByGitEmail(ctx, email)
	if !ok {
		miss[key] = true
		return store.User{}, false
	}
	cache[key] = u
	return u, true
}

func initialOf(s string) string {
	s = strings.TrimSpace(s)
	if s == "" {
		return "?"
	}
	r, _ := utf8.DecodeRuneInString(s)
	return strings.ToUpper(string(r))
}
