package com.binho.cosmicsdk.examples;

import com.binho.cosmicsdk.Types.DeviceInfo;
import com.binho.cosmicsdk.Types.I3cTargetInfo;

import java.util.Arrays;
import java.util.Set;

public final class ExampleHelpers {
    private ExampleHelpers() {
    }

    public static void assertStatus(int status, String operation, int... expected) {
        Set<Integer> expectedCodes = expected == null || expected.length == 0
                ? Set.of(0)
                : Arrays.stream(expected).boxed().collect(java.util.stream.Collectors.toSet());
        if (!expectedCodes.contains(status)) {
            String expectedText = expectedCodes.stream()
                    .map(code -> String.format("0x%04X", code))
                    .sorted()
                    .reduce((a, b) -> a + ", " + b)
                    .orElse("0x0000");
            throw new IllegalStateException(
                    operation + " failed. STATUS=" + String.format("0x%04X", status) + ". Expected: " + expectedText
            );
        }
    }

    public static void printDeviceInfo(DeviceInfo info) {
        System.out.println("Manufacturer: " + info.manufacturer());
        System.out.println("Product name: " + info.productName());
        System.out.println("Serial number: " + info.serialNumber());
        System.out.println("FW version: " + info.fwVersion());
        System.out.println("HW version: " + info.hwVersion());
    }

    public static void printPayload(String label, byte[] payload) {
        StringBuilder builder = new StringBuilder();
        for (byte b : payload) {
            builder.append(Byte.toUnsignedInt(b)).append(' ');
        }
        System.out.println(label + " [" + builder.toString().trim() + "]");
    }

    public static void printHexPayload(String label, byte[] payload) {
        StringBuilder builder = new StringBuilder();
        for (byte b : payload) {
            builder.append(String.format("0x%02X", Byte.toUnsignedInt(b))).append(' ');
        }
        System.out.println(label + " [" + builder.toString().trim() + "]");
    }

    public static void printTargetDeviceTable(Iterable<I3cTargetInfo> targets) {
        for (I3cTargetInfo target : targets) {
            System.out.println("\tStatic address: " + target.staticAddress());
            System.out.println("\tDynamic address: " + target.dynamicAddress());
            System.out.println("\tPID: " + Arrays.toString(target.pid()));
            System.out.println("\tBCR: " + Byte.toUnsignedInt(target.bcr().raw()));
            System.out.println("\tDCR: " + target.dcr());
            System.out.println("\tMWL: " + target.mwl());
            System.out.println("\tMRL: " + target.mrl());
            System.out.println("\tMax IBI payload length: " + target.maxIbiPayloadLength());
            System.out.println("\t-----------------------------------------------");
        }
    }
}
