package utils_test

import (
	"github.com/fiskerinc/cloud-services/services/optimus/utils"
	"testing"

	"github.com/fiskerinc/cloud-services/pkg/clickhouse"
	"github.com/fiskerinc/cloud-services/pkg/testhelper"
)

func TestNewVehicleMessageFilters(t *testing.T) {
	_ = utils.NewVehicleMessageFilters()
}

func TestNewFiltersForVehicle(t *testing.T) {
	conn := &clickhouse.MockConn{ExpectedResult: testFilters}
	client := clickhouse.NewMockClient(conn)

	vehicleFilters := utils.NewVehicleMessageFilters()
	filters := vehicleFilters.NewFiltersForVehicle(client, "TESTVIN123")

	if filters == nil {
		t.Errorf(testhelper.TestErrorTemplate, "TestNewFiltersForVehicle", "*MessageFilters", filters)
	}
}

func TestGetFiltersForVehicle(t *testing.T) {
	conn := &clickhouse.MockConn{ExpectedResult: testFilters}
	client := clickhouse.NewMockClient(conn)

	vehicleFilters := utils.NewVehicleMessageFilters()
	filters := vehicleFilters.GetFiltersForVehicle(client, "TESTVIN123")

	if filters == nil {
		t.Errorf(testhelper.TestErrorTemplate, "TestGetFiltersForVehicle", "*MessageFilters", filters)
	}
}

func TestSetDefaultFilters(t *testing.T) {
	vehicleFilters := utils.NewVehicleMessageFilters()
	vehicleFilters.SetDefaultFilters(testFilters)
}

func TestNewMessageFilters(t *testing.T) {
	_ = utils.NewMessageFilters()
}

func TestNewMessageFiltersFromDefault(t *testing.T) {
	d := utils.NewMessageFilters()
	d.SetMessageFilter(1, 1)

	f := utils.NewMessageFiltersFromDefault(d)
	if f.AllowMessage(1, 1) != true {
		t.Errorf(testhelper.TestErrorTemplate, "TestNewMessageFiltersFromDefault", true, false)
	}
}

func TestSetMessageFilter(t *testing.T) {
	f := utils.NewMessageFilters()
	f.SetMessageFilter(2, 2)
}

func TestPopulateFromClickhouse(t *testing.T) {
	f := utils.NewMessageFilters()
	f.PopulateFromClickhouse(testFilters)
	if f.AllowMessage(1, 1) != true {
		t.Errorf(testhelper.TestErrorTemplate, "TestPopulateFromClickhouse", true, false)
	}
}

func TestAllowMessage(t *testing.T) {
	f := utils.NewMessageFilters()
	f.PopulateFromClickhouse(testFilters)

	if f.AllowMessage(1, 1) != true {
		t.Errorf(testhelper.TestErrorTemplate, "TestAllowMessage", true, false)
	}

	if f.AllowMessage(3, 2) != true {
		t.Errorf(testhelper.TestErrorTemplate, "TestAllowMessage", true, false)
	}

	if f.AllowMessage(3, 1) == true {
		t.Errorf(testhelper.TestErrorTemplate, "TestAllowMessage", false, true)
	}

	if f.AllowMessage(5, 1) == true {
		t.Errorf(testhelper.TestErrorTemplate, "TestAllowMessage", false, true)
	}

	if f.AllowMessage(10, 1) != true {
		t.Errorf(testhelper.TestErrorTemplate, "TestAllowMessage", true, false)
	}
}

var testFilters = []clickhouse.CANFilterSchema{
	{
		ID:     1,
		Period: 2,
	},
	{
		ID:     3,
		Period: 4,
	},
	{
		ID:     5,
		Period: 0,
	},
	{
		ID:     10,
		Period: -1,
	},
}
