package gemini

import (
	"bytes"
	"crypto/tls"
	"errors"
	"io"
	"net"
	neturl "net/url"

	"tildegit.org/tjp/sliderule/internal/types"
)

// Client is used for sending gemini requests and parsing gemini responses.
//
// It carries no state and is usable and reusable simultaneously by multiple goroutines.
// The only reason you might create more than one Client is to support separate TLS-cert
// driven identities.
//
// The zero value is a usable Client with no client TLS certificate and which will not
// follow redirects.
type Client struct {
	MaxRedirects int

	tlsConf *tls.Config
}

// NewClient creates a gemini Client with the given TLS configuration and default MaxRedirects.
func NewClient(tlsConf *tls.Config) Client {
	return Client{tlsConf: tlsConf, MaxRedirects: DefaultMaxRedirects}
}

// DefaultMaxRedirects is the number of chained redirects a Client will perform for a
// single request by default. This can be changed by altering the MaxRedirects field.
const DefaultMaxRedirects int = 2

var ExceededMaxRedirects = errors.New("gemini.Client: exceeded MaxRedirects")

// RoundTrip sends a single gemini request to the correct server and returns its response.
//
// It also populates the TLSState and RemoteAddr fields on the request - the only field
// it needs populated beforehand is the URL.
//
// This method will not automatically follow redirects or cache permanent failures or
// redirects.
func (client Client) RoundTrip(request *types.Request) (*types.Response, error) {
	if request.Scheme != "gemini" && request.Scheme != "" {
		return nil, errors.New("non-gemini protocols not supported")
	}

	host := request.Host
	if _, port, _ := net.SplitHostPort(host); port == "" {
		host = net.JoinHostPort(host, "1965")
	}

	tlsConf := client.tlsConf
	if tlsConf == nil {
		tlsConf = &tls.Config{InsecureSkipVerify: true}
	}

	conn, err := tls.Dial("tcp", host, tlsConf)
	if err != nil {
		return nil, err
	}
	defer conn.Close()

	request.RemoteAddr = conn.RemoteAddr()
	st := conn.ConnectionState()
	request.TLSState = &st

	if _, err := conn.Write([]byte(request.URL.String() + "\r\n")); err != nil {
		return nil, err
	}

	response, err := ParseResponse(conn)
	if err != nil {
		return nil, err
	}

	// read and store the request body in full or we may miss doing so before
	// closing the connection
	bodybuf, err := io.ReadAll(response.Body)
	if err != nil {
		return nil, err
	}
	response.Body = bytes.NewBuffer(bodybuf)

	return response, nil
}

// Fetch parses a URL string and fetches the gemini resource.
//
// It will resolve any redirects along the way, up to client.MaxRedirects.
func (c Client) Fetch(url string) (*types.Response, error) {
	u, err := neturl.Parse(url)
	if err != nil {
		return nil, err
	}

	for i := 0; i <= c.MaxRedirects; i += 1 {
		response, err := c.RoundTrip(&types.Request{URL: u})
		if err != nil {
			return nil, err
		}
		if !c.IsRedirect(response) {
			return response, nil
		}

		prev := u
		u, err = neturl.Parse(response.Meta.(string))
		if err != nil {
			return nil, err
		}
		u = prev.ResolveReference(u)
	}

	return nil, ExceededMaxRedirects
}

func (c Client) IsRedirect(response *types.Response) bool {
	return ResponseCategoryForStatus(response.Status) == ResponseCategoryRedirect
}