package dbc_test

import (
	"testing"

	"github.com/fiskerinc/cloud-services/pkg/dbc"
	fm29_frs90 "github.com/fiskerinc/cloud-services/pkg/dbc/fm29_frs90"
	fm29_frsd0 "github.com/fiskerinc/cloud-services/pkg/dbc/fm29_frsd0"
	"github.com/fiskerinc/cloud-services/pkg/dbc/models"
	"github.com/fiskerinc/cloud-services/pkg/testhelper"
)

func TestNewDBCCollection(t *testing.T) {
	expected := "DBC 0e1f0e4eb01cfdd795f7f539d6baccc85770846050a83f5ac2f3ce75ea6453a0 already exists"

	collection := dbc.NewDBCCollection()
	if collection == nil {
		t.Error("collection is nil")
		return
	}

	// Should not error getting existing DBC
	_, err := collection.Get(fm29_frs90.Hash)
	if err != nil {
		t.Errorf(testhelper.TestErrorTemplate, "Get fm29_frs90", "no error", err)
	}

	// Should not error getting existing DBC
	_, err = collection.Get(fm29_frsd0.Hash)
	if err != nil {
		t.Errorf(testhelper.TestErrorTemplate, "Get fm29_frsd0", "no error", err)
	}

	// Should error getting non-existing DBC
	_, err = collection.Get("DOES NOT EXIST")
	if err == nil {
		t.Errorf(testhelper.TestErrorTemplate, "Get non-existing DBC", "error", err)
	}

	// Should panic if adding existing DBC hash
	defer func() {
		if err := recover(); err != nil {
			if err != expected {
				t.Errorf(testhelper.TestErrorTemplate, "AddVersion existing hash", expected, err)
			}
		}
	}()

	collection.AddVersion(fm29_frs90.Hash, dbc.NewFM29_FRS90_DBC())
	t.Errorf(testhelper.TestErrorTemplate, "AddVersion existing hash", "should have paniced", nil)
}

func TestGetShortKey(t *testing.T) {
	expected := "0e1f"
	key := models.GetShortKey(fm29_frs90.Hash)
	if key != expected {
		t.Errorf(testhelper.TestErrorTemplate, "GetShortKey", expected, key)
	}

	collection := dbc.NewDBCCollection()
	_, err := collection.Get(expected)
	if err != nil {
		t.Errorf(testhelper.TestErrorTemplate, "Get fm29_frs90", "no error", err)
	}
}

func TestDBCVersionAddMsgExisting(t *testing.T) {
	expected := "CAN message 816 already exists"

	// Should panic if adding existing message id
	defer func() {
		if err := recover(); err != nil {
			if err != expected {
				t.Errorf(testhelper.TestErrorTemplate, "AddMsg existing id", expected, err)
			}
		}
	}()

	dbc := dbc.NewFM29_FRS90_DBC()
	dbc.AddMsg(models.NewCANMessage(816, 14))
	t.Errorf(testhelper.TestErrorTemplate, "AddMsg existing id", "should have paniced", nil)
}

func TestDBCVersionAddSignalExisting(t *testing.T) {
	expected := "signal position 2 already exists"

	// Should panic if adding existing message id
	defer func() {
		if err := recover(); err != nil {
			if err != expected {
				t.Errorf(testhelper.TestErrorTemplate, "AddVersion existing hash", expected, err)
			}
		}
	}()

	msg := models.NewCANMessage(816, 14).
		Signal(1, "test1", nil).
		Signal(2, "test2", nil)

	msg.Signal(2, "test3", nil)
	t.Errorf(testhelper.TestErrorTemplate, "AddMsg existing id", "should have paniced", nil)
}
