package connection

import (
	"bytes"

	"github.com/lucas-clemente/quic-go"
	"github.com/lucas-clemente/quic-go/quicvarint"
)

type FrameWriteStreamImpl struct {
	stream quic.SendStream
}

func (f *FrameWriteStreamImpl) Write(d []byte) (int, error) {
	n, err := f.stream.Write(d)

	if err != nil {
		if quicErr, ok := err.(*quic.StreamError); ok {
			err = &StreamError{
				ErrCode: int64(quicErr.ErrorCode),
			}
		}
	}

	return n, err
}

func (f *FrameWriteStreamImpl) Close() error {
	return f.stream.Close()
}

func (f *FrameStreamImpl) Write(d []byte) (int, error) {
	n, err := f.stream.Write(d)

	if err != nil {
		if quicErr, ok := err.(*quic.StreamError); ok {
			err = &StreamError{
				ErrCode: int64(quicErr.ErrorCode),
			}
		}
	}

	return n, err
}

func writeHeader(str FrameWriteStream, frHeader *FrameHeader) error {
	buffer := &bytes.Buffer{}

	quicvarint.Write(buffer, uint64(frHeader.Type))
	quicvarint.Write(buffer, uint64(len(frHeader.Header)))
	quicvarint.Write(buffer, frHeader.BodyLength)

	buffer.Write(frHeader.Header)

	frameHeader := buffer.Bytes()
	headerLen := len(frameHeader)

	total := 0

	for total < headerLen {
		n, err := str.Write(frameHeader[total:])
		if err != nil {
			return err
		}

		total += n
	}

	return nil
}

func (f *FrameStreamImpl) Close() error {
	return f.stream.Close()
}
