--[[
 * Copyright (C) Rotorflight Project
 *
 * License GPLv3: https://www.gnu.org/licenses/gpl-3.0.en.html
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * 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.
 *
 * Note. Some icons have been sourced from https://www.flaticon.com/
]] --
local core = assert(rfsuite.compiler.loadfile("tasks/msp/api_core.lua"))()

-- Constants for MSP Commands
local API_NAME = "GOVERNOR_PROFILE" -- API name (must be same as filename)
local MSP_API_CMD_READ = 148 -- Command identifier 
local MSP_API_CMD_WRITE = 149 -- Command identifier 
local MSP_REBUILD_ON_WRITE = false -- Rebuild the payload on write 

local MSP_API_STRUCTURE_READ_DATA

if rfsuite.utils.apiVersionCompare(">=", "12.09") then

    local offOn = {"@i18n(api.GOVERNOR_PROFILE.tbl_off)@", "@i18n(api.GOVERNOR_PROFILE.tbl_on)@"}

    local governor_flags_bitmap = {
        { field = "fc_throttle_curve",    table = offOn, tableIdxInc = -1, help = "@i18n(api.GOVERNOR_PROFILE.fc_throttle_curve)@"},    -- bit 0
        { field = "tx_precomp_curve",     table = offOn, tableIdxInc = -1 , help = "@i18n(api.GOVERNOR_PROFILE.tx_precomp_curve)@"},    -- bit 1
        { field = "fallback_precomp",     table = offOn, tableIdxInc = -1 , help = "@i18n(api.GOVERNOR_PROFILE.fallback_precomp)@"},    -- bit 2
        { field = "voltage_comp",         table = offOn, tableIdxInc = -1 , help = "@i18n(api.GOVERNOR_PROFILE.voltage_comp)@"},    -- bit 3
        { field = "pid_spoolup",          table = offOn, tableIdxInc = -1 , help = "@i18n(api.GOVERNOR_PROFILE.pid_spoolup)@"},    -- bit 4
        { field = "hs_adjustment",        table = offOn, tableIdxInc = -1 , help = "@i18n(api.GOVERNOR_PROFILE.hs_adjustment)@"},    -- bit 5
        { field = "dyn_min_throttle",     table = offOn, tableIdxInc = -1 , help = "@i18n(api.GOVERNOR_PROFILE.dyn_min_throttle)@"},    -- bit 6
        { field = "autorotation",         table = offOn, tableIdxInc = -1 , help = "@i18n(api.GOVERNOR_PROFILE.autorotation)@"},    -- bit 7
        { field = "suspend",              table = offOn, tableIdxInc = -1 , help = "@i18n(api.GOVERNOR_PROFILE.suspend)@"},    -- bit 8
        { field = "bypass",               table = offOn, tableIdxInc = -1 , help = "@i18n(api.GOVERNOR_PROFILE.bypass)@"},    -- bit 9 (up to 15 bits can be defined)
    }

    MSP_API_STRUCTURE_READ_DATA = {
        {field = "governor_headspeed",            type = "U16", apiVersion = 12.09, simResponse = {208, 7}, min = 0,   max = 50000, default = 1000, unit = "rpm", step = 10, help ="@i18n(api.GOVERNOR_PROFILE.governor_headspeed)@"},
        {field = "governor_gain",                 type = "U8",  apiVersion = 12.09, simResponse = {100},    min = 0,   max = 250,   default = 40, help ="@i18n(api.GOVERNOR_PROFILE.governor_gain)@"},
        {field = "governor_p_gain",               type = "U8",  apiVersion = 12.09, simResponse = {10},     min = 0,   max = 250,   default = 40, help ="@i18n(api.GOVERNOR_PROFILE.governor_p_gain)@"},
        {field = "governor_i_gain",               type = "U8",  apiVersion = 12.09, simResponse = {125},    min = 0,   max = 250,   default = 50, help ="@i18n(api.GOVERNOR_PROFILE.governor_i_gain)@"},
        {field = "governor_d_gain",               type = "U8",  apiVersion = 12.09, simResponse = {5},      min = 0,   max = 250,   default = 0, help ="@i18n(api.GOVERNOR_PROFILE.governor_d_gain)@"},
        {field = "governor_f_gain",               type = "U8",  apiVersion = 12.09, simResponse = {20},     min = 0,   max = 250,   default = 10, help ="@i18n(api.GOVERNOR_PROFILE.governor_f_gain)@"},
        {field = "governor_tta_gain",             type = "U8",  apiVersion = 12.09, simResponse = {0},      min = 0,   max = 250,   default = 0, help ="@i18n(api.GOVERNOR_PROFILE.governor_tta_gain)@"},
        {field = "governor_tta_limit",            type = "U8",  apiVersion = 12.09, simResponse = {20},     min = 0,   max = 250,   default = 20,   unit = "%", help ="@i18n(api.GOVERNOR_PROFILE.governor_tta_limit)@"},
        {field = "governor_yaw_weight",           type = "U8",  apiVersion = 12.09, simResponse = {10},     min = 0,   max = 250,   default = 0, help ="@i18n(api.GOVERNOR_PROFILE.governor_yaw_weight)@"},
        {field = "governor_cyclic_weight",        type = "U8",  apiVersion = 12.09, simResponse = {40},     min = 0,   max = 250,   default = 10, help ="@i18n(api.GOVERNOR_PROFILE.governor_cyclic_weight)@"},
        {field = "governor_collective_weight",    type = "U8",  apiVersion = 12.09, simResponse = {100},    min = 0,   max = 250,   default = 100, help ="@i18n(api.GOVERNOR_PROFILE.governor_collective_weight)@"},
        {field = "governor_max_throttle",         type = "U8",  apiVersion = 12.09, simResponse = {100},    min = 40,  max = 100,   default = 100,  unit = "%", help ="@i18n(api.GOVERNOR_PROFILE.governor_max_throttle)@"},
        {field = "governor_min_throttle",         type = "U8",  apiVersion = 12.09, simResponse = {10},     min = 0,   max = 100,   default = 10,   unit = "%", help ="@i18n(api.GOVERNOR_PROFILE.governor_min_throttle)@"},
        {field = "governor_fallback_drop",        type = "U8",  apiVersion = 12.09, simResponse = {10},     min = 0,   max = 50,   default = 10,  unit = "%", help ="@i18n(api.GOVERNOR_PROFILE.governor_fallback_drop)@"},
        {field = "governor_flags",                type = "U16", apiVersion = 12.09, simResponse = {251, 3}, bitmap = governor_flags_bitmap, help ="@i18n(api.GOVERNOR_PROFILE.governor_flags)@"},
    }
else
    MSP_API_STRUCTURE_READ_DATA = {
        {field = "governor_headspeed",            type = "U16", apiVersion = 12.06, simResponse = {208, 7}, min = 0,   max = 50000, default = 1000, unit = "rpm", step = 10, help ="@i18n(api.GOVERNOR_PROFILE.governor_headspeed)@"},
        {field = "governor_gain",                 type = "U8",  apiVersion = 12.06, simResponse = {100},    min = 0,   max = 250,   default = 40, help ="@i18n(api.GOVERNOR_PROFILE.governor_gain)@"},
        {field = "governor_p_gain",               type = "U8",  apiVersion = 12.06, simResponse = {10},     min = 0,   max = 250,   default = 40, help ="@i18n(api.GOVERNOR_PROFILE.governor_p_gain)@"},
        {field = "governor_i_gain",               type = "U8",  apiVersion = 12.06, simResponse = {125},    min = 0,   max = 250,   default = 50, help ="@i18n(api.GOVERNOR_PROFILE.governor_i_gain)@"},
        {field = "governor_d_gain",               type = "U8",  apiVersion = 12.06, simResponse = {5},      min = 0,   max = 250,   default = 0, help ="@i18n(api.GOVERNOR_PROFILE.governor_d_gain)@"},
        {field = "governor_f_gain",               type = "U8",  apiVersion = 12.06, simResponse = {20},     min = 0,   max = 250,   default = 10, help ="@i18n(api.GOVERNOR_PROFILE.governor_f_gain)@"},
        {field = "governor_tta_gain",             type = "U8",  apiVersion = 12.06, simResponse = {0},      min = 0,   max = 250,   default = 0, help ="@i18n(api.GOVERNOR_PROFILE.governor_tta_gain)@"},
        {field = "governor_tta_limit",            type = "U8",  apiVersion = 12.06, simResponse = {20},     min = 0,   max = 250,   default = 20,   unit = "%", help ="@i18n(api.GOVERNOR_PROFILE.governor_tta_limit)@"},
        {field = "governor_yaw_ff_weight",        type = "U8",  apiVersion = 12.06, simResponse = {10},     min = 0,   max = 250,   default = 0, help ="@i18n(api.GOVERNOR_PROFILE.governor_yaw_ff_weight)@"},
        {field = "governor_cyclic_ff_weight",     type = "U8",  apiVersion = 12.06, simResponse = {40},     min = 0,   max = 250,   default = 10, help ="@i18n(api.GOVERNOR_PROFILE.governor_cyclic_ff_weight)@"},
        {field = "governor_collective_ff_weight", type = "U8",  apiVersion = 12.06, simResponse = {100},    min = 0,   max = 250,   default = 100, help ="@i18n(api.GOVERNOR_PROFILE.governor_collective_ff_weight)@"},
        {field = "governor_max_throttle",         type = "U8",  apiVersion = 12.06, simResponse = {100},    min = 40,  max = 100,   default = 100,  unit = "%", help ="@i18n(api.GOVERNOR_PROFILE.governor_max_throttle)@"},
        {field = "governor_min_throttle",         type = "U8",  apiVersion = 12.06, simResponse = {10},     min = 0,   max = 100,   default = 10,   unit = "%", help ="@i18n(api.GOVERNOR_PROFILE.governor_min_throttle)@"},
    }    
end

-- Process structure in one pass
local MSP_API_STRUCTURE_READ, MSP_MIN_BYTES, MSP_API_SIMULATOR_RESPONSE =
    core.prepareStructureData(MSP_API_STRUCTURE_READ_DATA)

-- set read structure
local MSP_API_STRUCTURE_WRITE = MSP_API_STRUCTURE_READ

-- Variable to store parsed MSP data
local mspData = nil
local mspWriteComplete = false
local payloadData = {}
local defaultData = {}

-- Create a new instance
local handlers = core.createHandlers()

-- Variables to store optional the UUID and timeout for payload
local MSP_API_UUID
local MSP_API_MSG_TIMEOUT


-- Track write completion without closures
local lastWriteUUID = nil
-- weak keys/values so finished entries don't pin memory
local writeDoneRegistry = setmetatable({}, { __mode = "kv" })


local function processReplyStaticRead(self, buf)
  core.parseMSPData(API_NAME, buf, self.structure, nil, nil, function(result)
    mspData = result
    if #buf >= (self.minBytes or 0) then
      local getComplete = self.getCompleteHandler
      if getComplete then
        local complete = getComplete()
        if complete then complete(self, buf) end
      end
    end
  end)
end

local function processReplyStaticWrite(self, buf)
  mspWriteComplete = true
  -- mark this UUID as completed (no module locals touched)
  if self.uuid then writeDoneRegistry[self.uuid] = true end

  local getComplete = self.getCompleteHandler
  if getComplete then
    local complete = getComplete()
    if complete then complete(self, buf) end
  end
end

local function errorHandlerStatic(self, buf)
  local getError = self.getErrorHandler
  if getError then
    local err = getError()
    if err then err(self, buf) end
  end
end

-- Function to initiate MSP read operation
local function read()
  if MSP_API_CMD_READ == nil then
    rfsuite.utils.log("No value set for MSP_API_CMD_READ", "debug")
    return
  end

  local message = {
    command           = MSP_API_CMD_READ,
    structure         = MSP_API_STRUCTURE_READ,   -- add this
    minBytes          = MSP_MIN_BYTES,            -- and this
    processReply      = processReplyStaticRead,
    errorHandler      = errorHandlerStatic,
    simulatorResponse = MSP_API_SIMULATOR_RESPONSE,
    uuid              = MSP_API_UUID,
    timeout           = MSP_API_MSG_TIMEOUT,
    getCompleteHandler = handlers.getCompleteHandler,
    getErrorHandler    = handlers.getErrorHandler,
    -- optional: place to stash parsed data if you want it here:
    mspData           = nil,
  }
  rfsuite.tasks.msp.mspQueue:add(message)
end

local function write(suppliedPayload)
  if MSP_API_CMD_WRITE == nil then
    rfsuite.utils.log("No value set for MSP_API_CMD_WRITE", "debug")
    return
  end

  -- Build payload eagerly (no capture)
  local payload = suppliedPayload or
    core.buildWritePayload(API_NAME, payloadData, MSP_API_STRUCTURE_WRITE, MSP_REBUILD_ON_WRITE)

  -- Choose a UUID for this write; if you already set MSP_API_UUID elsewhere, we’ll reuse it
  local uuid = MSP_API_UUID or rfsuite.utils and rfsuite.utils.uuid and rfsuite.utils.uuid() or tostring(os.clock())
  lastWriteUUID = uuid  -- track the most recent write without a closure

  local message = {
    command            = MSP_API_CMD_WRITE,
    payload            = payload,
    processReply       = processReplyStaticWrite, -- static, no upvalues
    errorHandler       = errorHandlerStatic,      -- static, no upvalues
    simulatorResponse  = {},

    uuid               = uuid,
    timeout            = MSP_API_MSG_TIMEOUT,

    -- provide handler getters so static callbacks can resolve at runtime
    getCompleteHandler = handlers.getCompleteHandler,
    getErrorHandler    = handlers.getErrorHandler,
  }

  rfsuite.tasks.msp.mspQueue:add(message)
end

-- Function to get the value of a specific field from MSP data
local function readValue(fieldName)
    if mspData and mspData['parsed'][fieldName] ~= nil then return mspData['parsed'][fieldName] end
    return nil
end

-- Function to set a value dynamically
local function setValue(fieldName, value)
    payloadData[fieldName] = value
end

-- Function to check if the read operation is complete
local function readComplete()
    return mspData ~= nil and #mspData['buffer'] >= MSP_MIN_BYTES
end

-- Function to check if the write operation is complete
local function writeComplete()
    return mspWriteComplete
end

-- Function to reset the write completion status
local function resetWriteStatus()
    mspWriteComplete = false
end

-- Function to return the parsed MSP data
local function data()
    return mspData
end

-- set the UUID for the payload
local function setUUID(uuid)
    MSP_API_UUID = uuid
end

-- set the timeout for the payload
local function setTimeout(timeout)
    MSP_API_MSG_TIMEOUT = timeout
end

-- Return the module's API functions
return {
    read = read,
    write = write,
    readComplete = readComplete,
    writeComplete = writeComplete,
    readValue = readValue,
    setValue = setValue,
    resetWriteStatus = resetWriteStatus,
    setCompleteHandler = handlers.setCompleteHandler,
    setErrorHandler = handlers.setErrorHandler,
    data = data,
    setUUID = setUUID,
    setTimeout = setTimeout
}
