package wire

import (
	

	
	
)

// A ConnectionCloseFrame is a CONNECTION_CLOSE frame
type ConnectionCloseFrame struct {
	IsApplicationError bool
	ErrorCode          uint64
	FrameType          uint64
	ReasonPhrase       string
}

func parseConnectionCloseFrame( []byte,  FrameType,  protocol.Version) (*ConnectionCloseFrame, int, error) {
	 := len()
	 := &ConnectionCloseFrame{IsApplicationError:  == FrameTypeApplicationClose}
	, ,  := quicvarint.Parse()
	if  != nil {
		return nil, 0, replaceUnexpectedEOF()
	}
	 = [:]
	.ErrorCode = 
	// read the Frame Type, if this is not an application error
	if !.IsApplicationError {
		, ,  := quicvarint.Parse()
		if  != nil {
			return nil, 0, replaceUnexpectedEOF()
		}
		 = [:]
		.FrameType = 
	}
	var  uint64
	, ,  = quicvarint.Parse()
	if  != nil {
		return nil, 0, replaceUnexpectedEOF()
	}
	 = [:]
	if int() > len() {
		return nil, 0, io.EOF
	}

	 := make([]byte, )
	copy(, )
	.ReasonPhrase = string()
	return ,  - len() + int(), nil
}

// Length of a written frame
func ( *ConnectionCloseFrame) (protocol.Version) protocol.ByteCount {
	 := 1 + protocol.ByteCount(quicvarint.Len(.ErrorCode)+quicvarint.Len(uint64(len(.ReasonPhrase)))) + protocol.ByteCount(len(.ReasonPhrase))
	if !.IsApplicationError {
		 += protocol.ByteCount(quicvarint.Len(.FrameType)) // for the frame type
	}
	return 
}

func ( *ConnectionCloseFrame) ( []byte,  protocol.Version) ([]byte, error) {
	if .IsApplicationError {
		 = append(, byte(FrameTypeApplicationClose))
	} else {
		 = append(, byte(FrameTypeConnectionClose))
	}

	 = quicvarint.Append(, .ErrorCode)
	if !.IsApplicationError {
		 = quicvarint.Append(, .FrameType)
	}
	 = quicvarint.Append(, uint64(len(.ReasonPhrase)))
	 = append(, []byte(.ReasonPhrase)...)
	return , nil
}