package renderer

import (
	"encoding/json"
	"html/template"
	"net/http"

	mobilityaccountsstorage "git.coopgo.io/coopgo-platform/mobility-accounts/storage"
)

const membersMenu = "members"

func (renderer *Renderer) MemberDisplay(w http.ResponseWriter, r *http.Request, admins any, groups []string) {
	files := renderer.ThemeConfig.GetStringSlice("views.members.display.files")

	state := NewState(r, renderer.ThemeConfig, membersMenu)
	state.ViewState = map[string]any{
		"admins": admins,
		"groups": groups,
	}
	renderer.Render("members_list", w, r, files, state)
}

func (renderer *Renderer) MemberUpdate(w http.ResponseWriter, r *http.Request, user any) {
	files := renderer.ThemeConfig.GetStringSlice("views.members.update.files")
	state := NewState(r, renderer.ThemeConfig, membersMenu)
	state.ViewState = user
	renderer.Render("members_update", w, r, files, state)
}

type MembersListState struct {
	Count   int                               `json:"count"`
	CacheId string                            `json:"cache_id"`
	Members []mobilityaccountsstorage.Account `json:"members"`
	Groups  []string                          `json:"groups"`
}

func (s MembersListState) JSON() template.JS {
	result, _ := json.Marshal(s)
	return template.JS(result)
}

func (s MembersListState) JSONWithLimits(a int, b int) template.JS {
	if b < len(s.Members) {
		s.Members = s.Members[a:b]
	}
	return s.JSON()
}

func (renderer *Renderer) MembersList(w http.ResponseWriter, r *http.Request, accounts []mobilityaccountsstorage.Account, cacheid string, groups []string) {
	files := renderer.ThemeConfig.GetStringSlice("views.members.list.files")

	state := NewState(r, renderer.ThemeConfig, membersMenu)

	state.ViewState = map[string]any{

		"list": MembersListState{
			Count:   len(accounts),
			CacheId: cacheid,
			Members: accounts,
			Groups:  groups,
		},
		"groups": groups,
	}

	renderer.Render("members_list", w, r, files, state)
}
