package com.binho.cosmicsdk.examples.i3c.hdrddr;

import com.binho.cosmicsdk.CosmicSdk;
import com.binho.cosmicsdk.ResultCodes;
import com.binho.cosmicsdk.Types.I2cTransferRate;
import com.binho.cosmicsdk.Types.I3cDriveStrength;
import com.binho.cosmicsdk.Types.I3cOpenDrainTransferRate;
import com.binho.cosmicsdk.Types.I3cPushPullRate;
import com.binho.cosmicsdk.Types.I3cTransferFlags;

import static com.binho.cosmicsdk.examples.ExampleHelpers.assertStatus;
import static com.binho.cosmicsdk.examples.ExampleHelpers.printDeviceInfo;
import static com.binho.cosmicsdk.examples.ExampleHelpers.printPayload;

public final class I3cHdrDdrExample {
    private I3cHdrDdrExample() {
    }

    public static void main(String[] args) {
        try (CosmicSdk sdk = new CosmicSdk(2000)) {
            if (!sdk.connect()) {
                throw new IllegalStateException("Failed to connect to a Binho device.");
            }

            var infoResult = sdk.getDeviceInfo();
            assertStatus(infoResult.status(), "getDeviceInfo");
            printDeviceInfo(infoResult.value());

            assertStatus(sdk.i3cSetBusVoltage(3300), "i3cSetBusVoltage");
            assertStatus(
                    sdk.i3cControllerInit(
                            I3cPushPullRate.PUSH_PULL_3_125_MHz_DC_31_25,
                            I3cOpenDrainTransferRate.OPEN_DRAIN_1_MHz,
                            I2cTransferRate.FAST_MODE,
                            I3cDriveStrength.STANDARD
                    ),
                    "i3cControllerInit",
                    ResultCodes.SUCCESS,
                    ResultCodes.FW_INTERFACE_ALREADY_INITIALIZED
            );
            assertStatus(sdk.i3cInitBus(), "i3cInitBus");

            assertStatus(sdk.i3cHdrDdrWrite(0x08, 0x04, new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}), "i3cHdrDdrWrite");
            assertStatus(sdk.i3cSdrWrite(0x08, new byte[]{0x00}, new byte[0], I3cTransferFlags.I3C_XFER_START_WITH_7E), "i3cSdrWrite(pointer reset)");

            var payload = sdk.i3cHdrDdrRead(0x08, 0x80, 10);
            assertStatus(payload.status(), "i3cHdrDdrRead");
            printPayload("Hdr-Ddr read:", payload.value());
        }
    }
}
