#include "LogicKiste_PortControl.h"

// ==========================================
// VIRTUELLE PORTS IMPLEMENTIERUNG
// ==========================================

LogicKiste_VirtualPort::LogicKiste_VirtualPort(int p0, int p1, int p2, int p3, int p4, int p5, int p6, int p7) {
  _pins[0] = p0; _pins[1] = p1; _pins[2] = p2; _pins[3] = p3;
  _pins[4] = p4; _pins[5] = p5; _pins[6] = p6; _pins[7] = p7;
  
  _pinCount = 0;
  for(int i=0; i<8; i++) {
    if(_pins[i] != -1) _pinCount++;
  }
}

void LogicKiste_VirtualPort::begin(uint8_t mode) {
  for(int i=0; i<_pinCount; i++) {
    if(_pins[i] != -1) {
      pinMode(_pins[i], mode);
    }
  }
}

void LogicKiste_VirtualPort::writePattern(const char* pattern) {
  for (int i = 0; i < _pinCount; i++) {
    if (pattern[i] == '\0') break; // Ende des Musters erreicht
    
    if (pattern[i] == '1') {
      digitalWrite(_pins[i], HIGH);
    } else if (pattern[i] == '0') {
      digitalWrite(_pins[i], LOW);
    }
    // Bei '_' überspringen wir den Pin (er bleibt wie er ist)
  }
}

bool LogicKiste_VirtualPort::checkPattern(const char* pattern) {
  for (int i = 0; i < _pinCount; i++) {
    if (pattern[i] == '\0') break;
    if (pattern[i] == 'X' || pattern[i] == 'x') continue; // Don't care
    
    bool bitState = digitalRead(_pins[i]);
    
    if (pattern[i] == '1' && !bitState) return false;
    if (pattern[i] == '0' && bitState) return false;
  }
  return true;
}