package ws

import 

// State represents state of websocket endpoint.
// It used by some functions to be more strict when checking compatibility with RFC6455.
type State uint8

const (
	// StateServerSide means that endpoint (caller) is a server.
	StateServerSide State = 0x1 << iota
	// StateClientSide means that endpoint (caller) is a client.
	StateClientSide
	// StateExtended means that extension was negotiated during handshake.
	StateExtended
	// StateFragmented means that endpoint (caller) has received fragmented
	// frame and waits for continuation parts.
	StateFragmented
)

// Is checks whether the s has v enabled.
func ( State) ( State) bool {
	return uint8()&uint8() != 0
}

// Set enables v state on s.
func ( State) ( State) State {
	return  | 
}

// Clear disables v state on s.
func ( State) ( State) State {
	return  & (^)
}

// ServerSide reports whether states represents server side.
func ( State) () bool { return .Is(StateServerSide) }

// ClientSide reports whether state represents client side.
func ( State) () bool { return .Is(StateClientSide) }

// Extended reports whether state is extended.
func ( State) () bool { return .Is(StateExtended) }

// Fragmented reports whether state is fragmented.
func ( State) () bool { return .Is(StateFragmented) }

// ProtocolError describes error during checking/parsing websocket frames or
// headers.
type ProtocolError string

// Error implements error interface.
func ( ProtocolError) () string { return string() }

// Errors used by the protocol checkers.
var (
	ErrProtocolOpCodeReserved             = ProtocolError("use of reserved op code")
	ErrProtocolControlPayloadOverflow     = ProtocolError("control frame payload limit exceeded")
	ErrProtocolControlNotFinal            = ProtocolError("control frame is not final")
	ErrProtocolNonZeroRsv                 = ProtocolError("non-zero rsv bits with no extension negotiated")
	ErrProtocolMaskRequired               = ProtocolError("frames from client to server must be masked")
	ErrProtocolMaskUnexpected             = ProtocolError("frames from server to client must be not masked")
	ErrProtocolContinuationExpected       = ProtocolError("unexpected non-continuation data frame")
	ErrProtocolContinuationUnexpected     = ProtocolError("unexpected continuation data frame")
	ErrProtocolStatusCodeNotInUse         = ProtocolError("status code is not in use")
	ErrProtocolStatusCodeApplicationLevel = ProtocolError("status code is only application level")
	ErrProtocolStatusCodeNoMeaning        = ProtocolError("status code has no meaning yet")
	ErrProtocolStatusCodeUnknown          = ProtocolError("status code is not defined in spec")
	ErrProtocolInvalidUTF8                = ProtocolError("invalid utf8 sequence in close reason")
)

// CheckHeader checks h to contain valid header data for given state s.
//
// Note that zero state (0) means that state is clean,
// neither server or client side, nor fragmented, nor extended.
func ( Header,  State) error {
	if .OpCode.IsReserved() {
		return ErrProtocolOpCodeReserved
	}
	if .OpCode.IsControl() {
		if .Length > MaxControlFramePayloadSize {
			return ErrProtocolControlPayloadOverflow
		}
		if !.Fin {
			return ErrProtocolControlNotFinal
		}
	}

	switch {
	// [RFC6455]: MUST be 0 unless an extension is negotiated that defines meanings for
	// non-zero values. If a nonzero value is received and none of the
	// negotiated extensions defines the meaning of such a nonzero value, the
	// receiving endpoint MUST _Fail the WebSocket Connection_.
	case .Rsv != 0 && !.Extended():
		return ErrProtocolNonZeroRsv

	// [RFC6455]: The server MUST close the connection upon receiving a frame that is not masked.
	// In this case, a server MAY send a Close frame with a status code of 1002 (protocol error)
	// as defined in Section 7.4.1. A server MUST NOT mask any frames that it sends to the client.
	// A client MUST close a connection if it detects a masked frame. In this case, it MAY use the
	// status code 1002 (protocol error) as defined in Section 7.4.1.
	case .ServerSide() && !.Masked:
		return ErrProtocolMaskRequired
	case .ClientSide() && .Masked:
		return ErrProtocolMaskUnexpected

	// [RFC6455]: See detailed explanation in 5.4 section.
	case .Fragmented() && !.OpCode.IsControl() && .OpCode != OpContinuation:
		return ErrProtocolContinuationExpected
	case !.Fragmented() && .OpCode == OpContinuation:
		return ErrProtocolContinuationUnexpected

	default:
		return nil
	}
}

// CheckCloseFrameData checks received close information
// to be valid RFC6455 compatible close info.
//
// Note that code.Empty() or code.IsAppLevel() will raise error.
//
// If endpoint sends close frame without status code (with frame.Length = 0),
// application should not check its payload.
func ( StatusCode,  string) error {
	switch {
	case .IsNotUsed():
		return ErrProtocolStatusCodeNotInUse

	case .IsProtocolReserved():
		return ErrProtocolStatusCodeApplicationLevel

	case  == StatusNoMeaningYet:
		return ErrProtocolStatusCodeNoMeaning

	case .IsProtocolSpec() && !.IsProtocolDefined():
		return ErrProtocolStatusCodeUnknown

	case !utf8.ValidString():
		return ErrProtocolInvalidUTF8

	default:
		return nil
	}
}