package localserver

import (
	"context"
	"encoding/json"
	"io"
	"net/http"
)

type (
	WebRTCHttpMiddleware struct {
		//menuItem *systray.MenuItem
	}
)

const (
	CREATE_HOSTED_SQUAD = "create_hosted_squad"
)

// func NewWebRTCHttpMiddleware(menuItem *systray.MenuItem) (webRTCHttpMiddleware *WebRTCHttpMiddleware) {
// 	webRTCHttpMiddleware = &WebRTCHttpMiddleware{
// 		menuItem: menuItem,
// 	}
// 	return
// }

func (wm *WebRTCHttpMiddleware) Process(ctx context.Context, req *http.Request) (err error) {
	done, errCh := make(chan struct{}), make(chan error)
	go func() {
		localServerReq, err := wm.unmarshallBody(req)
		if err != nil {
			errCh <- err
			return
		}
		switch localServerReq.ReqType {
		case CREATE_HOSTED_SQUAD:

		default:
		}
	}()
	select {
	case <-done:
		return
	case err = <-errCh:
		return
	case <-ctx.Done():
		err = ctx.Err()
		return
	}
}

func (wm *WebRTCHttpMiddleware) unmarshallBody(req *http.Request) (localServerReq *LocalServerRequest, err error) {
	reqBody, err := req.GetBody()
	if err != nil {
		return
	}
	bs, err := io.ReadAll(reqBody)
	if err != nil {
		return
	}
	err = json.Unmarshal(bs, &localServerReq)
	if err != nil {
		return
	}
	return
}
