package generation

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net"
	"net/http"
	"strings"

	"srs.epita.fr/fic-server/libfic"
)

var GeneratorSocket string

func doGeneration(uri string, contenttype string, buf io.Reader) (*http.Response, error) {
	sockType := "unix"
	if strings.Contains(GeneratorSocket, ":") {
		sockType = "tcp"
	}

	socket, err := net.Dial(sockType, GeneratorSocket)
	if err != nil {
		return nil, err
	}
	defer socket.Close()

	httpClient := &http.Client{
		Transport: &http.Transport{
			Dial: func(network, addr string) (net.Conn, error) {
				return socket, nil
			},
		},
	}

	return httpClient.Post("http://localhost"+uri, contenttype, buf)
}

func EnqueueGeneration(gs fic.GenStruct) (*http.Response, error) {
	buf, err := json.Marshal(gs)
	if err != nil {
		return nil, fmt.Errorf("Something is wrong with JSON encoder: %w", err)
	}

	return doGeneration("/enqueue", "application/json", bytes.NewReader(buf))
}

func PerformGeneration(gs fic.GenStruct) (*http.Response, error) {
	buf, err := json.Marshal(gs)
	if err != nil {
		return nil, fmt.Errorf("Something is wrong with JSON encoder: %w", err)
	}

	return doGeneration("/perform", "application/json", bytes.NewReader(buf))
}

func FullGeneration() (*http.Response, error) {
	return doGeneration("/full", "application/json", nil)
}
