#pragma once

#include <Wire.h>

class Tca9548a {
public:
  explicit Tca9548a(uint8_t address) : address_(address), activeChannel_(0xFF) {}

  bool begin() {
    Wire.beginTransmission(address_);
    return Wire.endTransmission() == 0;
  }

  bool selectChannel(uint8_t channel) {
    if (channel > 7) {
      return false;
    }

    const uint8_t mask = static_cast<uint8_t>(1u << channel);
    if (mask == activeChannel_) {
      return true;
    }

    Wire.beginTransmission(address_);
    Wire.write(mask);
    if (Wire.endTransmission() != 0) {
      return false;
    }

    activeChannel_ = mask;
    return true;
  }

  void disableAll() {
    Wire.beginTransmission(address_);
    Wire.write(0x00);
    Wire.endTransmission();
    activeChannel_ = 0x00;
  }

private:
  uint8_t address_;
  uint8_t activeChannel_;
};
