package gemini

import (
	"bufio"
	"errors"
	"io"
	"net/url"

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

// InvalidRequestLineEnding indicates that a gemini request didn't end with "\r\n".
var InvalidRequestLineEnding = errors.New("invalid request line ending")

// ParseRequest parses a single gemini request from a reader.
//
// If the reader argument is a *bufio.Reader, it will only read a single line from it.
func ParseRequest(rdr io.Reader) (*types.Request, error) {
	bufrdr, ok := rdr.(*bufio.Reader)
	if !ok {
		bufrdr = bufio.NewReader(rdr)
	}

	line, err := bufrdr.ReadString('\n')
	if err != io.EOF && err != nil {
		return nil, err
	}

	if len(line) < 2 || line[len(line)-2:] != "\r\n" {
		return nil, InvalidRequestLineEnding
	}

	u, err := url.Parse(line[:len(line)-2])
	if err != nil {
		return nil, err
	}

	if u.Scheme == "" {
		u.Scheme = "gemini"
	}

	return &types.Request{URL: u}, nil
}

// GetTitanRequestBody fetches the request body from a titan request.
//
// It returns nil if the argument is not a titan request or it otherwise
// does not have a request body set.
func GetTitanRequestBody(request *types.Request) io.Reader {
	if request.Scheme != "titan" {
		return nil
	}
	if rdr, ok := request.Meta.(io.Reader); ok {
		return rdr
	}
	return nil
}