#include "mux.h"

#include <zephyr/logging/log.h>
#include <stdlib.h>

LOG_MODULE_REGISTER(mux);

#define MUX_NODE DT_ALIAS(mux)

static const struct device *mux_dev = DEVICE_DT_GET(MUX_NODE);

int mux_init(void) {
	int ret;

	if (!DT_NODE_HAS_STATUS(MUX_NODE, okay)) {
		LOG_ERR("mux alias missing or disabled in devicetree");
		return -ENODEV;
	}

	if (!device_is_ready(mux_dev)) {
		LOG_ERR("Multiplexer device not ready");
		return -ENODEV;
	}

	ret = cd74hc4067_enable(mux_dev);
	if ((ret != 0) && (ret != -ENOTSUP)) {
		LOG_ERR("Failed to enable multiplexer: %d", ret);
		return ret;
	}

	ret = cd74hc4067_select_channel(mux_dev, 0U);
	if (ret != 0) {
		LOG_ERR("Failed to select initial channel: %d", ret);
		return ret;
	}

	LOG_INF("Multiplexer HAL initialized");

	return 0;
}

int mux_select_channel(int channel) {
    return cd74hc4067_select_channel(mux_dev, channel);
}