package nmos

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"strings"
	"time"
)

type ConnectionClient struct {
	BaseURL    string
	HTTPClient *http.Client
}

func NewConnectionClient(baseURL string) *ConnectionClient {
	return &ConnectionClient{
		BaseURL: strings.TrimRight(baseURL, "/"),
		HTTPClient: &http.Client{
			Timeout: 10 * time.Second,
		},
	}
}

func (c *ConnectionClient) StageReceiver(ctx context.Context, receiverID string, reqBody StagedReceiverRequest) error {
	body, err := json.Marshal(reqBody)
	if err != nil {
		return err
	}
	url := fmt.Sprintf("%s/x-nmos/connection/v1.1/receivers/%s/staged", c.BaseURL, receiverID)
	req, err := http.NewRequestWithContext(ctx, http.MethodPatch, url, bytes.NewReader(body))
	if err != nil {
		return err
	}
	req.Header.Set("Content-Type", "application/json")
	resp, err := c.HTTPClient.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode < 200 || resp.StatusCode >= 300 {
		return fmt.Errorf("NMOS IS-05 stage receiver returned %s", resp.Status)
	}
	return nil
}

func BuildRTPReceiverStagedRequest(senderID *string, sdp string) StagedReceiverRequest {
	transportFile := map[string]string{
		"data": sdp,
		"type": "application/sdp",
	}
	return StagedReceiverRequest{
		MasterEnable: true,
		Activation: Activation{
			Mode: "activate_immediate",
		},
		SenderID:      senderID,
		TransportFile: transportFile,
	}
}
