#include "FrontPanel.h"

void C_FrontPanel::Init() {
    Wire.begin();
    Wire.beginTransmission(MCP_ADDRESS);
    Wire.write(MCP_REG_IODIR);
    Wire.write(0x0F);  // buttons input, leds output
    Wire.write(0x0F);  // invert logic for buttons
    Wire.write(0x00);  // no interrupts
    Wire.endTransmission();

    Wire.beginTransmission(MCP_ADDRESS);
    Wire.write(MCP_REG_GPPU);
    Wire.write(0x0F);  // pullups for buttons
    Wire.endTransmission();
}

void C_FrontPanel::Tasks() {
    encPos = frontEnc.read();

    Wire.beginTransmission(MCP_ADDRESS);
    Wire.write(MCP_REG_OLAT);
    Wire.write(mcp_portVal & 0xF0);  //write data for LEDs
    Wire.endTransmission();

    Wire.beginTransmission(MCP_ADDRESS);
    Wire.write(MCP_REG_GPIO);
    Wire.endTransmission();
    Wire.requestFrom(MCP_ADDRESS, 1);
    if (Wire.available()) {
        mcp_portVal &= 0xF0;  //mask out button states from old data
        mcp_portVal |= Wire.read();
    }
}

void C_FrontPanel::SetLed(int ledIndex, bool state) {
    mcp_portVal &= ~(1 << (7 - ledIndex));          //mask out led state
    if (state) mcp_portVal |= 1 << (7 - ledIndex);  //set LED on when needed
}

bool C_FrontPanel::IsLedOn(int ledIndex) {
    return mcp_portVal & (1 << (7 - ledIndex));
}

bool C_FrontPanel::IsButtonDown(int btnIndex) {
    return mcp_portVal & (1 << (3 - btnIndex));
}

int C_FrontPanel::GetEncoderPos() {
    return encPos / 4;
}

bool C_FrontPanel::IsEncoderButtonDown() {
    return !digitalRead(12);
}