// Copyright 2012 Google, Inc. All rights reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree.
package layers

import (
	"fmt"
	"testing"

	"github.com/gopacket/gopacket"
)

// testPacketRadiotap0 is the packet:
//
//	09:34:34.799438 1.0 Mb/s 2412 MHz 11b -58dB signal antenna 7 Acknowledgment RA:88:1f:a1:ae:9d:cb
//	   0x0000:  0000 1200 2e48 0000 1002 6c09 a000 c607  .....H....l.....
//	   0x0010:  0000 d400 0000 881f a1ae 9dcb c630 4b4b  .............0KK
var testPacketRadiotap0 = []byte{
	0x00, 0x00, 0x12, 0x00, 0x2e, 0x48, 0x00, 0x00, 0x10, 0x02, 0x6c, 0x09, 0xa0, 0x00, 0xc6, 0x07,
	0x00, 0x00, 0xd4, 0x00, 0x00, 0x00, 0x88, 0x1f, 0xa1, 0xae, 0x9d, 0xcb, 0xc6, 0x30, 0x4b, 0x4b,
}

func TestPacketRadiotap0(t *testing.T) {
	p := gopacket.NewPacket(testPacketRadiotap0, LayerTypeRadioTap, gopacket.Default)
	if p.ErrorLayer() != nil {
		t.Error("Failed to decode packet:", p.ErrorLayer().Error())
	}
	checkLayers(p, []gopacket.LayerType{LayerTypeRadioTap, LayerTypeDot11}, t)
	rt := p.Layer(LayerTypeRadioTap).(*RadioTap)
	if rt.RadioTapValues[0].ChannelFrequency != 2412 || rt.RadioTapValues[0].DBMAntennaSignal != -58 || rt.RadioTapValues[0].Antenna != 7 {
		t.Error("Radiotap decode error")
	}
	if rt.RadioTapValues[0].Rate != 2 { // 500Kbps unit
		t.Error("Radiotap Rate decode error")
	}
}
func BenchmarkDecodePacketRadiotap0(b *testing.B) {
	for i := 0; i < b.N; i++ {
		gopacket.NewPacket(testPacketRadiotap0, LayerTypeRadioTap, gopacket.NoCopy)
	}
}

// testPacketRadiotap1 is the packet:
//
//	05:24:21.380948 2412 MHz 11g -36dB signal antenna 5 65.0 Mb/s MCS 7 20 MHz lon GI
//		0x0000:  0000 1500 2a48 0800 1000 6c09 8004 dc05  ....*H....l.....
//		0x0010:  0000 0700 0748 112c 0000 3a9d aaf0 191c  .....H.,..:.....
//		0x0020:  aba7 f213 9d00 3a9d aaf0 1970 b2ee a9f1  ......:....p....
//		0x0030:  16                                       .
var testPacketRadiotap1 = []byte{
	0x00, 0x00, 0x15, 0x00, 0x2a, 0x48, 0x08, 0x00, 0x10, 0x00, 0x6c, 0x09, 0x80, 0x04, 0xdc, 0x05,
	0x00, 0x00, 0x07, 0x00, 0x07, 0x48, 0x11, 0x2c, 0x00, 0x00, 0x3a, 0x9d, 0xaa, 0xf0, 0x19, 0x1c,
	0xab, 0xa7, 0xf2, 0x13, 0x9d, 0x00, 0x3a, 0x9d, 0xaa, 0xf0, 0x19, 0x70, 0xb2, 0xee, 0xa9, 0xf1,
	0x16,
}

func TestPacketRadiotap1(t *testing.T) {
	p := gopacket.NewPacket(testPacketRadiotap1, LayerTypeRadioTap, gopacket.Default)
	if p.ErrorLayer() != nil {
		t.Error("Failed to decode packet:", p.ErrorLayer().Error())
	}
	checkLayers(p, []gopacket.LayerType{LayerTypeRadioTap, LayerTypeDot11}, t)
	rt := p.Layer(LayerTypeRadioTap).(*RadioTap)
	if rt.RadioTapValues[0].ChannelFrequency != 2412 || rt.RadioTapValues[0].DBMAntennaSignal != -36 || rt.RadioTapValues[0].Antenna != 5 {
		t.Error("Radiotap decode error")
	}
	if !rt.RadioTapValues[0].MCS.Known.MCSIndex() || rt.RadioTapValues[0].MCS.MCS != 7 {
		t.Error("Radiotap MCS error")
	}
	if !rt.RadioTapValues[0].MCS.Known.Bandwidth() || rt.RadioTapValues[0].MCS.Flags.Bandwidth() != 0 {
		t.Error("Radiotap bandwidth error")
	}
	if !rt.RadioTapValues[0].MCS.Known.GuardInterval() || rt.RadioTapValues[0].MCS.Flags.ShortGI() {
		t.Error("Radiotap GI error")
	}
}
func BenchmarkDecodePacketRadiotap1(b *testing.B) {
	for i := 0; i < b.N; i++ {
		gopacket.NewPacket(testPacketRadiotap1, LayerTypeRadioTap, gopacket.NoCopy)
	}
}

// testPacketRadiotap2 is the packet:
//
//	09:34:34.799438 1.0 Mb/s 2412 MHz 11b -58dB signal antenna 7 Acknowledgment RA:88:1f:a1:ae:9d:cb
//	   0x0000:  0000 ff00 2e48 0000 1002 6c09 a000 c607  .....H....l.....
//	   0x0010:  0000 d400 0000 881f a1ae 9dcb c630 4b4b  .............0KK
//
// Test when the RadioTap size is too large, but still process the RadioTap
var testPacketRadiotap2 = []byte{
	0x00, 0x00, 0xff, 0x00, 0x2e, 0x48, 0x00, 0x00, 0x10, 0x02, 0x6c, 0x09, 0xa0, 0x00, 0xc6, 0x07,
	0x00, 0x00, 0xd4, 0x00, 0x00, 0x00, 0x88, 0x1f, 0xa1, 0xae, 0x9d, 0xcb, 0xc6, 0x30, 0x4b, 0x4b,
}

func TestPacketRadiotap2(t *testing.T) {
	p := gopacket.NewPacket(testPacketRadiotap2, LayerTypeRadioTap, gopacket.Default)
	if p.ErrorLayer() != nil {
		t.Error("Failed to decode packet:", p.ErrorLayer().Error())
	}
	checkLayers(p, []gopacket.LayerType{LayerTypeRadioTap}, t)
	rt := p.Layer(LayerTypeRadioTap).(*RadioTap)
	if rt.RadioTapValues[0].ChannelFrequency != 2412 || rt.RadioTapValues[0].DBMAntennaSignal != -58 || rt.RadioTapValues[0].Antenna != 7 {
		t.Error("Radiotap decode error")
	}
	if rt.RadioTapValues[0].Rate != 2 { // 500Kbps unit
		t.Error("Radiotap Rate decode error")
	}
}

// testPacketRadiotap3 is a HE-SU packet with a timestamp field
var testPacketRadiotap3 = []byte{
	0x00, 0x00, 0x4c, 0x00, 0x2b, 0x40, 0xd0, 0xa0, 0x20, 0x08, 0x00, 0xa0, 0x20, 0x08, 0x00, 0x00,
	0x27, 0xd7, 0x74, 0xdc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x14, 0x40, 0x01, 0xd8, 0x00,
	0x00, 0x00, 0x00, 0x00, 0x4f, 0x22, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
	0x27, 0xd7, 0x74, 0xdc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0xfc, 0xc7, 0x72, 0x00,
	0xc0, 0x28, 0x00, 0x00, 0x92, 0x80, 0x02, 0x0e, 0xd0, 0x00, 0xd8, 0x01, 0x88, 0x41, 0x38, 0x00,
	0x5c, 0xe9, 0x31, 0xff, 0xc3, 0x29, 0x84, 0x7b, 0x57, 0xfb, 0x4d, 0x11, 0x5c, 0xe9, 0x31, 0xff,
	0xc3, 0x27, 0x40, 0x9d, 0x10, 0xb8, 0xd3, 0x49, 0x00, 0x20, 0x4b, 0x00, 0x00, 0x00, 0x95, 0xcd,
	0xbe, 0xfd, 0xa5, 0xd2, 0xc9, 0x60, 0xd7, 0x0a, 0xdf, 0x7f, 0x21, 0xca, 0x38, 0xc4, 0xd4, 0x66,
	0x4c, 0xe0, 0xda, 0xc0, 0x01, 0x8b, 0x2a, 0xc1, 0x7f, 0xbf, 0xb4, 0x5d, 0x8b, 0xdb, 0xba, 0x83,
	0x76, 0x2f, 0x79, 0xd0, 0xc3, 0xf7, 0x08, 0xf1, 0xc9, 0x36, 0xbf, 0xb3, 0x24, 0x2d, 0xc9, 0xe8,
	0x53, 0x93, 0x85, 0x91, 0xe3, 0xfb,
}

func TestPacketRadiotap3(t *testing.T) {
	p := gopacket.NewPacket(testPacketRadiotap3, LayerTypeRadioTap, gopacket.Default)
	if p.ErrorLayer() != nil {
		t.Error("Failed to decode packet:", p.ErrorLayer().Error())
	}
	checkLayers(p, []gopacket.LayerType{LayerTypeRadioTap}, t)
	rt := p.Layer(LayerTypeRadioTap).(*RadioTap)

	if !rt.RadioTapValues[0].HE.Data1.DataMCSKnown() {
		t.Error("Radiotap HE Data1 MCS unknown")
	} else if rt.RadioTapValues[0].HE.Data3.DataMCS() != 8 {
		t.Error("Radiotap HE MCS error")
	}

	if !rt.RadioTapValues[0].HE.Data1.CodingKnown() {
		t.Error("Radiotap HE Data1 Coding unknown")
	} else if rt.RadioTapValues[0].HE.Data3.Coding() != RadiotapHECodingLDPC {
		t.Error("Radiotap HE Coding error")
	}

	if !rt.RadioTapValues[0].HE.Data1.BeamChangeKnown() {
		t.Error("Radiotap HE Data1 Beam Change unknown")
	} else if !rt.RadioTapValues[0].HE.Data3.BeamChange() {
		t.Error("Radiotap HE Beam Change error")
	}

	if rt.RadioTapValues[0].HE.Data5.DataBandwidth() != DataBandwidth80 {
		t.Error("Radiotap HE Bandwidth error")
	}

	if rt.RadioTapValues[0].HE.Data1.HE_PPDUFormat() != RadiotapHePpduFormatHE_SU {
		t.Error("Radiotap HE PPDU Format error")
	}
}

// testPacketRadiotap4 is a beacon packet with multiple radiotap namespaces
var testPacketRadiotap4 = []byte{
	0x0, 0x0, 0x30, 0x0, 0x2e, 0x40, 0x40, 0xa0, 0x20, 0x8, 0x0, 0xa0, 0x20, 0x8, 0x0, 0x0, 0x10,
	0x2, 0x71, 0x9, 0xa0, 0x0, 0xea, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xf4, 0x0, 0xf0,
	0x23, 0x0, 0x0, 0x0, 0x0, 0x16, 0x0, 0x11, 0x3, 0xe9, 0x0, 0xea, 0x1, 0x80, 0x0, 0x0, 0x0, 0xff,
	0xff, 0xff, 0xff, 0xff, 0xff, 0x60, 0x38, 0xe0, 0x30, 0x77, 0xf5, 0x60, 0x38, 0xe0, 0x30, 0x77,
	0xf5, 0xd0, 0x7f, 0x9b, 0x61, 0xb4, 0xaf, 0xe9, 0x1, 0x0, 0x0, 0x64, 0x0, 0x11, 0x4, 0x0, 0xc,
	0x4c, 0x69, 0x6e, 0x6b, 0x73, 0x79, 0x73, 0x31, 0x35, 0x37, 0x34, 0x33, 0x1, 0x8, 0x82, 0x84, 0x8b,
	0x96, 0x12, 0x24, 0x48, 0x6c, 0x3, 0x1, 0x2, 0x5, 0x4, 0x0, 0x1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 0x18, 0x0, 0x50, 0xf2, 0x2, 0x1, 0x1, 0x0, 0x0, 0x3, 0xa4, 0x0, 0x0, 0x27,
	0xa4, 0x0, 0x0, 0x42, 0x43, 0x5e, 0x0, 0x62, 0x32, 0x2f, 0x0, 0xdd, 0x7, 0x0, 0xc, 0x43, 0xf, 0x0,
	0x0, 0x0, 0xdd, 0x21, 0x0, 0xc, 0xe7, 0x8, 0x0, 0x0, 0x0, 0xbf, 0xc, 0xb1, 0x1, 0xc0, 0x33, 0x2a,
	0xff, 0x92, 0x4, 0x2a, 0xff, 0x92, 0x4, 0xc0, 0x5, 0x0, 0x0, 0x0, 0x2a, 0xff, 0xc3, 0x3, 0x1, 0x2,
	0x2, 0x80, 0x50, 0x82, 0x4,
}

func TestPacketRadiotap4(t *testing.T) {
	p := gopacket.NewPacket(testPacketRadiotap4, LayerTypeRadioTap, gopacket.Default)
	if p.ErrorLayer() != nil {
		t.Error("Failed to decode packet:", p.ErrorLayer().Error())
	}
	checkLayers(p, []gopacket.LayerType{LayerTypeRadioTap}, t)
	rt := p.Layer(LayerTypeRadioTap).(*RadioTap)

	if len(rt.Present) != 3 {
		t.Errorf("Expected 3 Present bitmap sets in packet, got %d", len(rt.Present))
	}
	if len(rt.RadioTapValues) != 3 {
		t.Errorf("Expected 3 RadioTap namespaces in packet, got %d", len(rt.RadioTapValues))
	}

	// all three present bitmaps should have antenna dbm
	for presentInd, present := range rt.Present {
		if presentInd != 0 && !present.Antenna() {
			t.Errorf("Expected RadioTap namespace %d to have antenna number present", presentInd)
		}
		if !present.DBMAntennaSignal() {
			t.Errorf("Expected RadioTap namespace %d to have dBm antenna signal field present", presentInd)
		}
		if rt.RadioTapValues[presentInd].DBMAntennaSignal == 0 {
			t.Errorf("Expected RadioTap namespace %d to have non-zero dBm antenna signal field", presentInd)
		}
		if presentInd == 2 && rt.RadioTapValues[presentInd].Antenna != 1 {
			t.Errorf("Expected antenna ID in RadioTap namespace %d to be 1, but got %d", presentInd, rt.RadioTapValues[presentInd].Antenna)
		}
	}
}

func TestSerializeRadioTapRoundTrip(t *testing.T) {
	cases := [][]byte{
		testPacketRadiotap0,
		testPacketRadiotap1,
		//testPacketRadiotap3,
		testPacketRadiotap4,
	}

	for i, testPacket := range cases {
		t.Run(fmt.Sprintf("RoundTrip_radiotapPacket%d", i), func(t *testing.T) {
			p := gopacket.NewPacket(testPacket, LayerTypeRadioTap, gopacket.Default)
			if p.ErrorLayer() != nil {
				t.Fatal("Failed to decode packet:", p.ErrorLayer().Error())
			}
			rt := p.Layer(LayerTypeRadioTap).(*RadioTap)

			// Serialize the RadioTap layer
			buf := gopacket.NewSerializeBuffer()
			err := rt.SerializeTo(buf, gopacket.SerializeOptions{FixLengths: true})
			if err != nil {
				t.Fatal("Failed to serialize RadioTap layer:", err)
			}

			serialized := buf.Bytes()
			if len(serialized) != int(rt.Length) {
				t.Fatalf("Expected serialized RadioTap length %d, got %d", rt.Length, len(serialized))
			}

			// Create a new packet from the serialized data
			newP := gopacket.NewPacket(serialized, LayerTypeRadioTap, gopacket.Default)
			if newP.ErrorLayer() != nil {
				t.Fatal("Failed to decode serialized packet:", newP.ErrorLayer().Error())
			}

			// Check if the original and new RadioTap layers are equal
			newRt := newP.Layer(LayerTypeRadioTap).(*RadioTap)

			if rt.Length != newRt.Length {
				t.Errorf("Expected serialized RadioTap length %d, got %d", rt.Length, newRt.Length)
			}
			if len(rt.RadioTapValues) != len(newRt.RadioTapValues) {
				t.Errorf("Expected %d RadioTap values, got %d", len(rt.RadioTapValues), len(newRt.RadioTapValues))
			}
			for i := range rt.RadioTapValues {
				if rt.RadioTapValues[i].ChannelFrequency != newRt.RadioTapValues[i].ChannelFrequency ||
					rt.RadioTapValues[i].DBMAntennaSignal != newRt.RadioTapValues[i].DBMAntennaSignal ||
					rt.RadioTapValues[i].Antenna != newRt.RadioTapValues[i].Antenna ||
					rt.RadioTapValues[i].Rate != newRt.RadioTapValues[i].Rate {
					t.Errorf("RadioTap value mismatch at index %d", i)
				}
			}
		})
	}
}
