package application

import (
	"context"
	"crypto/rand"
	"encoding/base64"
	"fmt"
	"io"
	"net/http"
	"time"

	"git.coopgo.io/coopgo-apps/parcoursmob/utils/identification"
	"git.coopgo.io/coopgo-platform/groups-management/storage"
	accounts "git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
)

func (h *ApplicationHandler) GroupSettingsDisplay(w http.ResponseWriter, r *http.Request) {
	g := r.Context().Value(identification.GroupKey)
	if g == nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	group := g.(storage.Group)

	members, err := h.members()
	if err != nil {
		if err != nil {
			fmt.Println(err)
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
	}

	admins := []any{}
	groupMembers := []any{}

	for _, m := range members {
		mm := m.ToStorageType()
		for _, g := range mm.Data["groups"].([]any) {
			if g.(string) == group.ID {
				groupMembers = append(groupMembers, mm)
			}
			if g.(string) == group.ID+":admin" {
				admins = append(admins, mm)
			}
		}
	}

	h.Renderer.GroupSettingsDisplay(w, r, group, groupMembers, admins)
}

func (h *ApplicationHandler) GroupSettingsInviteMember(w http.ResponseWriter, r *http.Request) {
	g := r.Context().Value(identification.GroupKey)
	if g == nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	group := g.(storage.Group)

	r.ParseForm()

	accountresp, err := h.services.GRPC.MobilityAccounts.GetAccountUsername(context.TODO(), &accounts.GetAccountUsernameRequest{
		Username:  r.FormValue("username"),
		Namespace: "parcoursmob",
	})

	if err == nil {
		// Account already exists : adding the existing account to admin list
		account := accountresp.Account.ToStorageType()
		//account.Data["groups"] = append(account.Data["groups"].([]any), groupid, groupid)
		account.Data["groups"] = append(account.Data["groups"].([]any), group.ID)

		as, _ := accounts.AccountFromStorageType(&account)

		_, err = h.services.GRPC.MobilityAccounts.UpdateData(
			context.TODO(),
			&accounts.UpdateDataRequest{
				Account: as,
			},
		)

		fmt.Println(err)

		data := map[string]any{
			"group": group.Data["name"],
		}

		if err := h.emailing.Send("onboarding.existing_member", r.FormValue("username"), data); err != nil {
			fmt.Println(err)
		}

		http.Redirect(w, r, "/app/group/settings", http.StatusFound)
		return
	} else {
		// Onboard now administrator
		onboarding := map[string]any{
			"username": r.FormValue("username"),
			"group":    group.ID,
			"admin":    false,
		}

		b := make([]byte, 16)
		if _, err := io.ReadFull(rand.Reader, b); err != nil {
			fmt.Println(err)
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		key := base64.RawURLEncoding.EncodeToString(b)

		h.cache.PutWithTTL("onboarding/"+key, onboarding, 72*time.Hour)

		data := map[string]any{
			"group": group.Data["name"],
			"key":   key,
		}

		if err := h.emailing.Send("onboarding.new_member", r.FormValue("username"), data); err != nil {
			fmt.Println(err)
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
	}

	http.Redirect(w, r, "/app/group/settings", http.StatusFound)
	return
}
