#include <stdlib.h>
#include <unistd.h>
#include "unity.h"
#include "parity.h"
#include "unity_test_module.h"
#include "encode.h"

// Macro om zonder regelnummers te testen
#define MY_RUN_TEST(func) RUN_TEST(func, 0)

extern void encode_setUp(void) {}
extern void encode_tearDown(void) {}

void test_encode_get_nibbles_normal(void) {
    uint8_t high, low;
    encode_get_nibbles(0xAB, &high, &low);
    TEST_ASSERT_EQUAL_UINT8(0x0A, high); // High nibble of 0xAB is 0xA
    TEST_ASSERT_EQUAL_UINT8(0x0B, low);  // Low nibble of 0xAB is 0xB
}

void test_encode_get_nibbles_null_ptrs(void) {
    encode_get_nibbles(0xAA, NULL, NULL); // Should not crash
}

void test_encode_value_normal(void) {
    uint8_t high, low;
    encode_value(0x41, &high, &low); 
    //0x41 = 01000001 --> nibHigh = 0x04, and nibLow = 0x01
    // Format: [0][d3][d2][d1][d0][p2][p1][p0] (MSB first)
    //high: 0 0100 101 --> 0x25
    //low:  0 0001 111 --> 0x0F
    TEST_ASSERT_EQUAL_HEX8(0x25, high);
    TEST_ASSERT_EQUAL_HEX8(0x0F, low);
}

void test_encode_value_null_pointers(void) {
    encode_value(0x55, NULL, NULL); // Should not crash
}

void test_encode_value_all_zeros(void) {
    uint8_t high, low;
    encode_value(0x00, &high, &low);
    TEST_ASSERT_EQUAL_UINT8(0x00, high);
    TEST_ASSERT_EQUAL_UINT8(0x00, low);
}

void test_encode_nibble_values(void) {
    TEST_ASSERT_EQUAL_UINT8(0x00, encode_nibble(0x00));  // All zeros
    TEST_ASSERT_EQUAL_UINT8(0x7F, encode_nibble(0x0F));  // All ones in nibble
    TEST_ASSERT_EQUAL_UINT8(0x55, encode_nibble(0x0A));  // 1010 pattern
}

void run_encode_tests() {
    UnityRegisterSetupTearDown(encode_setUp, encode_tearDown);

    MY_RUN_TEST(test_encode_get_nibbles_normal);
    MY_RUN_TEST(test_encode_get_nibbles_null_ptrs);
    MY_RUN_TEST(test_encode_value_normal);
    MY_RUN_TEST(test_encode_value_null_pointers);
    MY_RUN_TEST(test_encode_value_all_zeros);
    MY_RUN_TEST(test_encode_nibble_values);

    UnityUnregisterSetupTearDown();
}
