/**
 *
 * @license MIT License
 *
 * Copyright (c) 2026 lewis he
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 * @file      AW9364LedDriver.hpp
 * @author    Lewis He (lewishe@outlook.com)
 * @date      2026-03-03
 */

#pragma once

#include "IoExpanderBase.hpp"

/** @brief Maximum brightness steps (0‑16). */
constexpr uint8_t MAX_BRIGHTNESS_STEPS = 16;

/**
 * @class AW9364LedDriver
 * @brief Controls LED brightness by generating a specific number of pulses on a GPIO pin.
 *
 * The driver toggles the pin rapidly to produce a perceived brightness level.
 * It can operate either directly on an Arduino pin or via an IoExpanderBase
 * (e.g., an I2C GPIO expander).
 *
 * @warning When using an I2C expander, the I2C bus speed must be set to 1 MHz;
 *          lower speeds will cause insufficient pulse rate and incorrect brightness.
 */
class AW9364LedDriver
{
public:
    /**
     * @brief Initialize the driver for use with a native Arduino pin.
     *
     * @param pin Arduino pin number (must support OUTPUT mode).
     */
    void begin(uint8_t pin)
    {
        _driver_pin = pin;
        _base = nullptr;
        this->_pinMode(_driver_pin, OUTPUT);
        this->_digitalWrite(_driver_pin, LOW);
    }

    /**
     * @brief Initialize the driver for use with a GPIO expander pin.
     *
     * @param base Reference to an IoExpanderBase instance (e.g., XL9555).
     * @param pin  Pin number on the expander (0‑pinCount‑1).
     *
     * @warning The I2C bus speed of the expander MUST be configured to 1 MHz
     *          before calling this function. Failure to do so will result in
     *          incorrect brightness levels.
     */
    void begin(IoExpanderBase &base, uint8_t pin)
    {
        _base = &base;
        _driver_pin = pin;
        this->_pinMode(_driver_pin, OUTPUT);
        this->_digitalWrite(_driver_pin, LOW);
    }

    /**
     * @brief Set the LED brightness level.
     *
     * Brightness is controlled by the number of pulses generated.
     * A value of 0 turns the LED off (pin LOW). Non‑zero values are mapped to
     * a number of pulses that adjust the brightness upward or downward from
     * the current setting. Pulses are generated by quickly toggling the pin
     * LOW→HIGH.
     *
     * @param value Desired brightness (0‑16). Values >16 are clamped to 16.
     *
     * @note When using an I2C expander, ensure the bus speed is 1 MHz; otherwise
     *       the pulse timing will be incorrect.
     */
    void setBrightness(uint8_t value)
    {
        if (_brightness == value) {
            return;
        }
        if (value > MAX_BRIGHTNESS_STEPS) {
            value = MAX_BRIGHTNESS_STEPS;
        }

        // Turn off if brightness is zero
        if (value == 0) {
            this->_digitalWrite(_driver_pin, 0);
            _brightness = 0;
            return;
        }

        // If coming from zero, start with a HIGH pulse to enable output
        if (_brightness == 0) {
            this->_digitalWrite(_driver_pin, 1);
            _brightness = MAX_BRIGHTNESS_STEPS;
        }

        // Calculate number of pulses needed to change from current brightness
        int from = MAX_BRIGHTNESS_STEPS - _brightness;
        int to   = MAX_BRIGHTNESS_STEPS - value;
        int num  = (MAX_BRIGHTNESS_STEPS + to - from) % MAX_BRIGHTNESS_STEPS;

        /*  // Optional speed boost when using I2C expanders
        //  uint32_t frequency = 0;
        //  if (_base) {
        //      // Increasing I2C speed may be necessary for enough pulse rate.
        //      // Tested with XL9555: can run at 1000 kHz despite 400 kHz spec.
        //      frequency = _base->getClock();
        //      _base->setClock(1000000UL);
        //  }
        */

        // Generate the required number of pulses
        for (int i = 0; i < num; i++) {
            this->_digitalWrite(_driver_pin, 0);
            this->_digitalWrite(_driver_pin, 1);
        }

        /*  // Restore original communication speed
        //  if (_base) {
        //      _base->setClock(frequency);
        //  }
        */

        _brightness = value;
    }

    /**
     * @brief Get the current brightness setting.
     *
     * @return uint8_t Current brightness (0‑16).
     */
    uint8_t getBrightness() const
    {
        return _brightness;
    }

protected:
    /**
     * @brief Internal helper to set pin mode, handling both native and expander pins.
     *
     * @param pin  Pin number.
     * @param mode INPUT or OUTPUT.
     */
    void _pinMode(uint8_t pin, uint8_t mode)
    {
        if (_base) {
            _base->pinMode(pin, mode);
        } else {
            pinMode(pin, mode);
        }
    }

    /**
     * @brief Internal helper to write digital value, handling both native and expander pins.
     *
     * @param pin   Pin number.
     * @param value HIGH (true) or LOW (false).
     */
    void _digitalWrite(uint8_t pin, uint8_t value)
    {
        if (_base) {
            _base->digitalWrite(pin, value);
        } else {
            digitalWrite(pin, value);
        }
    }

private:
    IoExpanderBase *_base;          ///< Pointer to expander instance (nullptr when using native pins)
    uint8_t _driver_pin;             ///< Pin number used for LED control
    uint8_t _brightness = 0;         ///< Current brightness level (0‑16)
};
