#ifndef POT_H
#define POT_H

#include <ArduinoLog.h>
#include "../config.h"
#include <osr-base.h>
#include <App.h>
#include <Component.h>
#include "types.h"
#include <xmath.h>

#ifdef PLATFORM_PORTENTA_H7_M7
#include <Arduino_MachineControl.h>
using namespace machinecontrol;
float res_divider = 0.28057;
float reference = 24;
#endif
// test relay::info <<400;2;64;400:info:1:0>>
// test relay::clearFlag <<400;2;64;400:clearFlag:1:0>>

class POT : public Component, public ModbusValue<int>
{

public:
    POT(
        Component *owner,
        short _pin,
        short _id,
        short _addr) : ModbusValue<int>(_addr, MB_FC::MB_FC_READ_REGISTERS),
                       Component("POT", _id, Component::COMPONENT_DEFAULT, owner),
                       pin(_pin),
                       last_value(0)
                       //registerMode(MB_REGISTER_MODE::E_MB_REGISTER_MODE_NONE)
    {
        SBI(nFlags, OBJECT_NET_CAPS::E_NCAPS_MODBUS);
        setRegisterMode(MB_REGISTER_MODE::E_MB_REGISTER_MODE_READ);
    }
    short setup()
    {
#ifdef PLATFORM_PORTENTA_H7_M7
        analogReadResolution(16);
        analog_in.set0_10V();
#endif
        last_value = loop();
        return E_OK;
    }

    short debug()
    {
// Log.verbose(F("POT:debug pin=%d value=%d" CR), pin, value);
#ifdef PLATFORM_PORTENTA_H7_M7
        Log.verbose(F("POT:debug pin=%d value=%d | %d" CR), pin, value, analog_in.read(pin));
#else
        info(0, 0);
#endif
        return E_OK;
    }
    short info(short val0, short val1)
    {
        Log.verboseln("POT::info - Pin=%d | Key=%d | Addr=%d | Val=%d | NetVal=%d ", pin, id, addr, value, netVal());
        return E_OK;
    }
    short loop()
    {
        if (now - last < ANALOG_POT_READ_INTERVAL)
        {
            return E_OK;
        }
        last = now;
#ifdef PLATFORM_PORTENTA_H7_M7
        float raw_voltage_ch0 = analog_in.read(pin);
        float voltage_ch0 = (raw_voltage_ch0 * reference) / 65535 / res_divider;
        value = voltage_ch0;
#else
        value = analogRead(pin);
#endif
        onSet(value);
        return value;
    }

    short onRegisterMethods(Bridge *bridge)
    {
        bridge->registerMemberFunction(id, this, C_STR("setFlag"), (ComponentFnPtr)&POT::setFlag);
        //bridge->registerMemberFunction(id, this, C_STR("clearFlag"), (ComponentFnPtr)&POT::clearFlag);
        bridge->registerMemberFunction(id, this, C_STR("info"), (ComponentFnPtr)&POT::info);
        return E_OK;
    }
    short pin;
    int value;
    int last_value;
};

#endif
