package server

import (
	"html/template"
	"net/http"
	"strconv"
	"strings"

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

type noteRender struct {
	RepoPath string
	Post     string
	CSRF     string
	Count    string
	Toggle   string
	ViewerID int64
}

func buildNoteRows(notes []store.Note, lang i18n.Lang, opt noteRender) []NoteRow {
	rows := make([]NoteRow, len(notes))
	index := map[int64]int{}
	for i, n := range notes {
		rows[i] = NoteRow{
			ID: n.ID, Author: n.Author, Body: n.Body, Path: n.FilePath,
			Start: n.LineStart, End: n.LineEnd, HasSuggestion: n.Suggestion != "",
			When: i18n.FormatDate(lang, n.CreatedAt), At: n.CreatedAt, ParentID: n.ParentID,
			HTML: template.HTML(markdown.RenderTasks(n.Body, "", "", opt.RepoPath, markdown.Tasks{
				Post: opt.Post, CSRF: opt.CSRF, Kind: "mr-note", ID: strconv.FormatInt(n.ID, 10),
				CanToggle: opt.ViewerID != 0 && opt.ViewerID == n.AuthorID, Count: opt.Count, Toggle: opt.Toggle,
			})),
		}
		index[n.ID] = i
	}
	for i := range rows {
		parent := rows[i].ParentID
		if parent == 0 {
			continue
		}
		pi, ok := index[parent]
		if !ok || rows[pi].ParentID != 0 {
			rows[i].ParentID = 0
			continue
		}
		rows[pi].Replies = append(rows[pi].Replies, rows[i])
	}
	return rows
}

func arrangeNotes(notes []store.Note, files []gitrepo.DiffFile, lang i18n.Lang, opt noteRender) ([]NoteRow, []DiffFileView) {
	rows := buildNoteRows(notes, lang, opt)
	placed := map[int64]bool{}
	var views []DiffFileView
	for _, f := range files {
		view := DiffFileView{Path: f.Path}
		for _, ln := range f.Lines {
			row := DiffLineView{Kind: ln.Kind, Text: ln.Text, Old: ln.Old, New: ln.New}
			if ln.New > 0 {
				for _, note := range rows {
					if note.ParentID != 0 {
						continue
					}
					if note.Path == f.Path && note.End == ln.New {
						row.Notes = append(row.Notes, note)
						placed[note.ID] = true
					}
				}
			}
			view.Lines = append(view.Lines, row)
		}
		views = append(views, view)
	}
	var general []NoteRow
	for _, note := range rows {
		if note.ParentID != 0 {
			continue
		}
		if note.Path == "" || !placed[note.ID] {
			general = append(general, note)
		}
	}
	return general, views
}

func repoPath(raw string) (string, bool) {
	raw = strings.TrimSpace(raw)
	if raw == "" {
		return "", true
	}
	p := strings.ReplaceAll(raw, `\`, "/")
	if strings.HasPrefix(p, "/") || strings.Contains(p, "..") || strings.ContainsAny(p, "\r\n") {
		return "", false
	}
	return p, true
}

func (s *Server) applySuggestions(w http.ResponseWriter, r *http.Request) {
	u, repo, _, ok := s.guard(w, r, access.RoleDeveloper)
	if !ok || !s.csrfOK(w, r) {
		return
	}
	n, err := strconv.ParseInt(r.PathValue("number"), 10, 64)
	if err != nil {
		http.NotFound(w, r)
		return
	}
	back := repoURL(repo) + "/-/merge-requests/" + r.PathValue("number")
	var ids []int64
	for _, raw := range r.Form["id"] {
		id, err := strconv.ParseInt(raw, 10, 64)
		if err == nil {
			ids = append(ids, id)
		}
	}
	if !s.uiOK(w, r, back, s.opApplySuggestions(r.Context(), u, repo, n, r.FormValue("title"), r.FormValue("description"), ids)) {
		return
	}
	s.redirect(w, r, back, s.tr(r, "flash.suggestions"), "")
}
