#include <Encoder.h>
#include <WiFi.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define MAX_DISPLAYED_NETWORKS 5 // Maximum number of networks displayed at once
#define switchPin 12
Encoder encoder(6, 14); // Initialize the rotary encoder
int encoderPos = 0; // Current position of the encoder
int startIndex = 0; // Index of the first displayed network

void setup() {
  Serial.begin(115200);
  Wire.begin();
  pinMode(switchPin, INPUT_PULLUP);

  display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS);
  display.display();
  delay(2000);

  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(0, 0);
  display.println("Enter WiFi SSID:");
  display.display();
  display.clearDisplay();
  display.display();
}

void loop() {
  handleSSID();
  handleEncoder();
}

void handleSSID() {
  int numNetworks = WiFi.scanNetworks();
  Serial.println("Scan done!");
  
  if (numNetworks == 0) {
    Serial.println("No networks found.");
    return;
  } 

  Serial.println();
  Serial.print(numNetworks);
  Serial.println(" networks found");
  
  for (int i = startIndex; i < min(startIndex + MAX_DISPLAYED_NETWORKS, numNetworks); ++i) {
    // Print SSID and RSSI for each network found
    int displayIndex = i - startIndex;
    display.setCursor(0, (displayIndex * 17));
    display.print(i + 1);
    display.print(":");
    display.print(WiFi.SSID(i));
    display.print("(");
    display.print(WiFi.RSSI(i));
    display.print(")");
    display.print((WiFi.encryptionType(i) == WIFI_AUTH_OPEN) ? " " : "*");
    display.display();
    delay(10);
  }

  delay(100); // Add a small delay to prevent flickering
}

void handleEncoder() {
  int newPos = encoder.read(); // Read the current position of the encoder
  
  if (newPos != encoderPos) { // Check if the position has changed
    if (newPos > encoderPos) { // Encoder rotated clockwise
      scrollMenu(true);
    } else { // Encoder rotated counter-clockwise
      scrollMenu(false);
    }
    encoderPos = newPos; // Update the encoder position
  }
}

void scrollMenu(bool direction) {
  int numNetworks = WiFi.scanNetworks();
  if (direction == true && startIndex < numNetworks - MAX_DISPLAYED_NETWORKS) {
    startIndex++;
  } else if (direction == false && startIndex > 0) {
    startIndex--;
  }
}