/**
 * Marlin 3D Printer Firmware
 * Copyright (c) 2024 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
 *
 * Based on Sprinter and grbl.
 * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 */
#pragma once

#include <Arduino.h>
#include "HAL.h"

#ifndef NUM_DIGITAL_PINS
  #error "Expected NUM_DIGITAL_PINS not found."
#endif

/**
 *  Life gets complicated if you want an easy to use 'M43 I' output (in port/pin order)
 *  because the variants in this platform do not always define all the I/O port/pins
 *  that a CPU has.
 *
 *  VARIABLES:
 *     Ard_num - Arduino pin number - defined by the platform. It is used by digitalRead and
 *               digitalWrite commands and by M42.
 *             - does not contain port/pin info
 *             - is not in port/pin order
 *             - typically a variant will only assign Ard_num to port/pins that are actually used
 *     Index - M43 counter - only used to get Ard_num
 *     x - a parameter/argument used to search the pin_array to try to find a signal name
 *         associated with a Ard_num
 *     Port_pin - port number and pin number for use with CPU registers and printing reports
 *
 *  Since M43 uses digitalRead and digitalWrite commands, only the Port_pins with an Ard_num
 *  are accessed and/or displayed.
 *
 *  Three arrays are used.
 *
 *  digitalPin[] is provided by the platform.  It consists of the Port_pin numbers in
 *  Arduino pin number order.
 *
 *  pin_array is a structure generated by the pins/pinsDebug.h header file.  It is generated by
 *  the preprocessor. Only the signals associated with enabled options are in this table.
 *  It contains:
 *    - name of the signal
 *    - the Ard_num assigned by the pins_YOUR_BOARD.h file using the platform defines.
 *        EXAMPLE:  "#define KILL_PIN  PB1" results in Ard_num of 57.  57 is then used as the
 *                  argument to digitalPinToPinName(IO) to get the Port_pin number
 *    - if it is a digital or analog signal.  PWMs are considered digital here.
 *
 *  pin_xref is a structure generated by this header file.  It is generated by the
 *  preprocessor. It is in port/pin order.  It contains just the port/pin numbers defined by the
 *  platform for this variant.
 *    - Ard_num
 *    - printable version of Port_pin
 *
 *  Routines with an "x" as a parameter/argument are used to search the pin_array to try to
 *  find a signal name associated with a port/pin.
 *
 *  NOTE -  the Arduino pin number is what is used by the M42 command, NOT the port/pin for that
 *          signal.  The Arduino pin number is listed by the M43 I command.
 */

/**
 * Pins Debugging for RP2040
 *
 *   - NUMBER_PINS_TOTAL
 *   - MULTI_NAME_PAD
 *   - getPinByIndex(index)
 *   - printPinNameByIndex(index)
 *   - getPinIsDigitalByIndex(index)
 *   - digitalPinToAnalogIndex(pin)
 *   - getValidPinMode(pin)
 *   - isValidPin(pin)
 *   - isAnalogPin(pin)
 *   - digitalRead_mod(pin)
 *   - pwm_status(pin)
 *   - printPinPWM(pin)
 *   - printPinPort(pin)
 *   - printPinNumber(pin)
 *   - printPinAnalog(pin)
 */

#define NUMBER_PINS_TOTAL NUM_DIGITAL_PINS
#define NUM_ANALOG_FIRST A0

#define MODE_PIN_INPUT  0 // Input mode (reset state)
#define MODE_PIN_OUTPUT 1 // General purpose output mode
#define MODE_PIN_ALT    2 // Alternate function mode
#define MODE_PIN_ANALOG 3 // Analog mode

#define getPinByIndex(x) pin_array[x].pin
#define printPinNameByIndex(x) do{ sprintf_P(buffer, PSTR("%-" STRINGIFY(MAX_NAME_LENGTH) "s"), pin_array[x].name); SERIAL_ECHO(buffer); }while(0)
#define getPinIsDigitalByIndex(x) pin_array[x].is_digital
#define digitalPinToAnalogIndex(P) digital_pin_to_analog_pin(P)

uint8_t get_pin_mode(const pin_t pin) {
  // Check if pin is in alternate function mode (I2C, SPI, etc.)
  const uint32_t gpio_func = gpio_get_function(pin);

  // GPIO_FUNC_I2C is typically function 3 on RP2040
  if ( gpio_func == GPIO_FUNC_I2C
    || gpio_func == GPIO_FUNC_SPI
    || gpio_func == GPIO_FUNC_UART
    || gpio_func == GPIO_FUNC_PWM
  ) {
    return MODE_PIN_ALT;
  }

  // For GPIO mode, check direction
  return gpio_get_dir(pin) ? MODE_PIN_OUTPUT : MODE_PIN_INPUT;
}

bool getValidPinMode(const pin_t pin) {
  const uint8_t pin_mode = get_pin_mode(pin);
  return pin_mode == MODE_PIN_OUTPUT || pin_mode == MODE_PIN_ALT;  // assume all alt definitions are PWM
}

#define isValidPin(P) WITHIN(P, 0, pin_t(NUMBER_PINS_TOTAL - 1))

int8_t digital_pin_to_analog_pin(pin_t pin) {
  pin -= NUM_ANALOG_FIRST;
  return (WITHIN(pin, 0, NUM_ANALOG_INPUTS - 1)) ? pin : -1;
}

bool isAnalogPin(const pin_t pin) {
  return digital_pin_to_analog_pin(pin) != -1;
}

#define digitalRead_mod(A) extDigitalRead(A)  // must use Arduino pin numbers when doing reads
#define printPinNumber(P) do{ sprintf_P(buffer, PSTR("%3d "), P); SERIAL_ECHO(buffer); }while(0)
#define printPinAnalog(P) do{ sprintf_P(buffer, PSTR(" (A%2d)  "), digitalPinToAnalogIndex(P)); SERIAL_ECHO(buffer); }while(0)
#define MULTI_NAME_PAD 33 // space needed to be pretty if not first name assigned to a pin

//bool is_digital(const pin_t pin) {
//  const uint8_t pin_mode = get_pin_mode(pin);
//  return pin_mode == MODE_PIN_INPUT || pin_mode == MODE_PIN_OUTPUT;
//}

bool pwm_status(const pin_t pin) {
  // Check if this pin is configured for PWM
  return PWM_PIN(pin) && get_pin_mode(pin) == MODE_PIN_ALT;
}

void printPinPWM(const pin_t pin) {
  if (pwm_status(pin)) {
    // RP2040 has hardware PWM on specific pins
    char buffer[22];
    sprintf_P(buffer, PSTR("PWM:  pin %d  "), pin);
    SERIAL_ECHO(buffer);
  }
}

void printPinPort(const pin_t pin) {}
