#include <stdlib.h>
#include <unistd.h> // for close()

#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)

// Setup/teardown hooks
extern void encode_setUp(void) {}
extern void encode_tearDown(void) {}

/// --- TEST: encode_get_nibbles ---

void test_encode_get_nibbles_normal(void) {
    uint8_t high, low;
    encode_get_nibbles(0xAB, &high, &low); // 0xAB = 10101011
    TEST_ASSERT_EQUAL_UINT8(0x0A, high);   // 1010
    TEST_ASSERT_EQUAL_UINT8(0x0B, low);    // 1011
}

void test_encode_get_nibbles_null_ptrs(void) {
    uint8_t value = 0xAA;
    encode_get_nibbles(value, NULL, NULL); // mag niet crashen
    // Geen assert nodig; slaagt bij geen crash
}

void test_encode_value_normal(void) {
    uint8_t high, low;
    encode_value(0xAC, &high, &low);  // 0xA = 1010, 0xC = 1100
    TEST_ASSERT_EQUAL_UINT8(add_parity(0xA), high);
    TEST_ASSERT_EQUAL_UINT8(add_parity(0xC), low);
}

void test_encode_value_null_pointers(void) {
    encode_value(0x55, NULL, NULL); // mag niet crashen
}

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

void test_encode_value_all_ones(void) {
    uint8_t high, low;
    encode_value(0xFF, &high, &low);
    TEST_ASSERT_EQUAL_UINT8(add_parity(0x0F), high); // 1111
    TEST_ASSERT_EQUAL_UINT8(add_parity(0x0F), low);  // 1111
}

void test_encode_value_output_differs_from_input(void) {
    uint8_t input = 0x3C;
    uint8_t high, low;
    encode_value(input, &high, &low);
    TEST_ASSERT_NOT_EQUAL(input, high);
    TEST_ASSERT_NOT_EQUAL(input, low);
}

void test_encode_value_is_consistent(void) {
    uint8_t h1, l1, h2, l2;
    encode_value(0x6E, &h1, &l1);
    encode_value(0x6E, &h2, &l2);
    TEST_ASSERT_EQUAL_UINT8(h1, h2);
    TEST_ASSERT_EQUAL_UINT8(l1, l2);
}


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_value_all_ones);
    MY_RUN_TEST(test_encode_value_output_differs_from_input);
    MY_RUN_TEST(test_encode_value_is_consistent);

    UnityUnregisterSetupTearDown();
}
