#define IN_SWITCH_INVERT false
#define IN_SWITCH_PULLUP false

#define IN_SWITCH_NUM 6
#define PINOUT_WATER_BANK_FLOAT_SWITCH_LOWER 26
#define PINOUT_WATER_BANK_FLOAT_SWITCH_UPPER 27
#define PINOUT_STERILIZATION_CHAMBER_FLOAT_SWITCH_LOWER 33
#define PINOUT_STERILIZATION_CHAMBER_FLOAT_SWITCH_UPPER 25
#define PINOUT_STERILIZED_CHAMBER_FLOAT_SWITCH_LOWER 32
#define PINOUT_STERILIZED_CHAMBER_FLOAT_SWITCH_UPPER 35

#define WATER_BANK_FLOAT_SWITCH_LOWER 0
#define WATER_BANK_FLOAT_SWITCH_UPPER 1
#define STERILIZATION_CHAMBER_FLOAT_SWITCH_LOWER 2
#define STERILIZATION_CHAMBER_FLOAT_SWITCH_UPPER 3
#define STERILIZED_CHAMBER_FLOAT_SWITCH_LOWER 4
#define STERILIZED_CHAMBER_FLOAT_SWITCH_UPPER 5

static byte IN_SWITCH_OFF = LOW;
static byte IN_SWITCH_ON = HIGH;

static int8_t inSwitchPin[IN_SWITCH_NUM] = {PINOUT_WATER_BANK_FLOAT_SWITCH_LOWER,
                                            PINOUT_WATER_BANK_FLOAT_SWITCH_UPPER,
                                            PINOUT_STERILIZATION_CHAMBER_FLOAT_SWITCH_LOWER,
                                            PINOUT_STERILIZATION_CHAMBER_FLOAT_SWITCH_UPPER,
                                            PINOUT_STERILIZED_CHAMBER_FLOAT_SWITCH_LOWER,
                                            PINOUT_STERILIZED_CHAMBER_FLOAT_SWITCH_UPPER
                                            };

static byte inSwitchState[IN_SWITCH_NUM];

void ClearInSwitch(){
  for (int i=0; i<IN_SWITCH_NUM; i++){
    int8_t pin = inSwitchPin[i];
    //if (pin>=0){
      inSwitchState[i] = IN_SWITCH_OFF;
    //}
  } 
}

void InitInSwitchHandler(){
  if (!IN_SWITCH_INVERT){
    IN_SWITCH_OFF = LOW;
    IN_SWITCH_ON = HIGH;
  }else{
    IN_SWITCH_OFF = LOW;
    IN_SWITCH_ON = HIGH;    
  }

  ClearInSwitch();
  
  for (int i=0; i<IN_SWITCH_NUM; i++){
    int8_t pin = inSwitchPin[i];
    if ((pin>=0) && ((pin>=34 && pin<=36) || (pin==39))){
      //Input only pins (should be use external pull up)
      pinMode(pin, INPUT);
    }else if (pin>=0){
      //use internal pullup
      if (IN_SWITCH_PULLUP){
        pinMode(pin, INPUT_PULLUP);
      }else{
        pinMode(pin, INPUT_PULLDOWN);
      }
    }
  }
}

void RefreshInSwitchState(){
  for (int i=0; i<IN_SWITCH_NUM; i++){
    int8_t pin = inSwitchPin[i];
    if (pin>=0){
      inSwitchState[i] = digitalRead(pin);
    }
  }
}

bool GetInSwitchState(byte idx){
  if (idx<0 || idx>=IN_SWITCH_NUM) return false;
  return (inSwitchState[idx] == IN_SWITCH_ON);
}

//used for unit test
void SetInSwitchState(byte idx, bool state){
  if (idx<0 || idx>=IN_SWITCH_NUM) return;
  inSwitchState[idx] = state?IN_SWITCH_ON:IN_SWITCH_OFF;
}

