#include <MD_MAX72xx.h>

int	MAX_DEVICES =	1;

const int maxX = MAX_DEVICES * 8 - 1;
const int maxY = 7;

int	CLK_PIN	=	13;
int	DATA_PIN	= 11;
int	CS_PIN	=	10;

int Y_pin = 0;
int X_pin = 1;
int SW_pin = 2;

MD_MAX72XX mx = MD_MAX72XX(MD_MAX72XX::PAROLA_HW, CS_PIN, MAX_DEVICES);

int x = 0;
int y = 0;

int middleXvalue = 512;
int middleYvalue = 512;
int offset = 30;

byte ledRow = B10000000;
int Yposition = 0;
int Xposition = 0;

int delayTime = 300;

void setup() {
  mx.begin();
  mx.control(MD_MAX72XX::INTENSITY, MAX_INTENSITY / 2);
  mx.clear();

  pinMode(Y_pin, INPUT);
  pinMode(X_pin, INPUT);
  pinMode(SW_pin, INPUT_PULLUP);

  Serial.begin(9600);

  mx.setRow(0,0,ledRow);
}


void loop() {

  //check if the joystick is pushed to the right
  if (analogRead(X_pin) < (middleXvalue - offset)) {
    // check if we're in the rightmost column
    if(Xposition == 7){
      Serial.print("You're in the rightmost column already \n\n");
    }
    else {
      ledRow = ledRow >> 1;
      mx.setRow(0,Yposition,ledRow);
      Xposition = Xposition + 1;
    }
    
  }

  // check if the joystick is pushed to the left
  if (analogRead(X_pin) > (middleXvalue + offset)){
    // check if we're in the leftmost column
    if(Xposition == 0){
      Serial.print("You're in the leftmost column already \n\n");
    }
    else {
      ledRow = ledRow << 1;
      mx.setRow(0,Yposition,ledRow);
      Xposition = Xposition - 1;
    }
  }

  // check if the joystick is pushed up
  if(analogRead(Y_pin) > (middleYvalue + offset)){
    //check if we're in the topmost row
    if(Yposition == 0){
      Serial.print("You're in the topmost row \n\n");
    }
    else{
      Yposition = Yposition - 1;
      mx.setRow(0,Yposition, ledRow); //new row to what was previously in old row
      mx.setRow(0, Yposition+1, 0); //old row to zeros
    }
  }

  // check if the joystick is pushed down
  if(analogRead(Y_pin) < (middleYvalue - offset)){
    //check if we're in the bottom row
    if(Yposition == 7){
      Serial.print("You're in the bottom row \n\n");
    }
    else{
      Yposition = Yposition + 1;
      mx.setRow(0,Yposition, ledRow); //new row to what was previously in old row
      mx.setRow(0, Yposition-1, 0); //old row to zeros
    }
  }

  delay(delayTime);
  
}