package icsrtp

import (
	"encoding/binary"

	"gitlab.com/ics_cinnamon/voicegateway/icspacketparser"
)

type RTP struct {
	Version       int
	Mark          int
	PayloadType   icspacketparser.PayloadType
	Seq           uint16
	Timestamp     uint32
	SSID          uint32
	PayloadLen    int
	Payload       []byte
	RtpHeaderByte []byte
}

const RTPHeaderLen = 12

func NewRTP(mark, pt, seq, ts, ssrc int, payload []byte) *RTP {
	rtp := RTP{}

	rtp.RtpHeaderByte = make([]byte, RTPHeaderLen)

	//version, padding, extension, cc
	rtp.RtpHeaderByte[0] = 0x80
	//fmt.Printf("v %b\n", rtp.RtpHeaderByte[0])

	//mark, payload type
	m := byte(0xff & (mark << 7))
	p := byte(0xff) & byte(pt)
	rtp.RtpHeaderByte[1] = m | p
	/*
		fmt.Printf("m %b\n", m)
		fmt.Printf("p %b\n", p)
	*/

	//sequence
	o := make([]byte, 4)
	binary.BigEndian.PutUint16(o, uint16(seq))
	//o := ByteOrdering(uint(seq), 2, true)
	/*
		rtp.RtpHeaderByte[2] = o[1]
		rtp.RtpHeaderByte[3] = o[0]
	*/
	copy(rtp.RtpHeaderByte[2:4], o[:2])
	//fmt.Printf("seq: %d - %d|%d\n", seq, o[0], o[1])
	/*
		fmt.Printf("seq: %d - %d[%b]\n",
			uint(seq),
			uint16(rtp.RtpHeaderByte[2])|uint16(rtp.RtpHeaderByte[3])<<8,
			uint16(rtp.RtpHeaderByte[2])|uint16(rtp.RtpHeaderByte[3])<<8)
	*/

	//timestamp
	//o = ByteOrdering(uint(ts), 4, true)
	binary.BigEndian.PutUint32(o, uint32(ts))
	/*
		rtp.RtpHeaderByte[4] = o[3]
		rtp.RtpHeaderByte[5] = o[2]
		rtp.RtpHeaderByte[6] = o[1]
		rtp.RtpHeaderByte[7] = o[0]
	*/
	copy(rtp.RtpHeaderByte[4:8], o[:])
	/*
		fmt.Printf("time now %d, %d\n",
			uint32(ts),
			uint32(rtp.RtpHeaderByte[4])|uint32(rtp.RtpHeaderByte[5])<<8|uint32(rtp.RtpHeaderByte[6])<<16|uint32(rtp.RtpHeaderByte[7])<<24)
	*/

	//ssrc
	//o = ByteOrdering(uint(ssrc), 4, true)
	binary.BigEndian.PutUint32(o, uint32(ssrc))
	/*
		rtp.RtpHeaderByte[8] = o[3]
		rtp.RtpHeaderByte[9] = o[2]
		rtp.RtpHeaderByte[10] = o[1]
		rtp.RtpHeaderByte[11] = o[0]
	*/
	copy(rtp.RtpHeaderByte[8:], o[:])
	/*
		fmt.Printf("ssrc %x, %x\n",
			uint32(ssrc),
			uint32(rtp.RtpHeaderByte[8])|uint32(rtp.RtpHeaderByte[9])<<8|uint32(rtp.RtpHeaderByte[10])<<16|uint32(rtp.RtpHeaderByte[11])<<24)
	*/

	rtp.Payload = make([]byte, len(payload))
	copy(rtp.Payload, payload)

	return &rtp
}

func (r RTP) Byte() []byte {
	payloadLen := len(r.Payload)
	ret := make([]byte, payloadLen+RTPHeaderLen)

	offset := copy(ret, r.RtpHeaderByte)
	copy(ret[offset:], r.Payload)

	return ret
}
