-- Copyright (c) 2026 Huawei Technologies Co., Ltd.
-- openUBMC is licensed under Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at:
--          http://license.coscl.org.cn/MulanPSL2
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
-- EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
-- MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
-- See the Mulan PSL v2 for more details.

local core = require('dbus.core')
local utils = require('mc.utils')
local bus_base = require('dbus.bus_base')
local skynet = require('skynet')
local sd_bus = require('sd_bus')
local json = require('cjson')
local log = require('mc.logging')
local shm = core.SharedMemory
local binary_to_dbus_type = utils.binary_to_dbus_type
local fork = skynet.fork
local allocate_object_id = utils.allocate_object_id
local shm_object_lock_exec = utils.shm_object_lock_exec
local shm_object_lock_shared_exec = utils.shm_object_lock_shared_exec

local DBUS_SERVICE_NAME <const> = 'bmc.kepler.hwproxy'
local SD_BUS_VTABLE_PROPERTY_ERROR <const> = bus_base.SD_BUS_VTABLE_PROPERTY_ERROR
local SD_BUS_VTABLE_PROPERTY_EMITS_INVALIDATION <const> = bus_base.SD_BUS_VTABLE_PROPERTY_EMITS_INVALIDATION
local SD_BUS_VTABLE_DISABLE_SHM_CACHE <const> = bus_base.SD_BUS_VTABLE_DISABLE_SHM_CACHE

local g_tree
local g_dbus
local shared_object = {}

local object_values_t = {}

function object_values_t:__index(name)
    return self.interface:get_prop_value(name)
end

function object_values_t:__newindex(name, value)
    self.interface:set_prop_value(name, value)
end

local object_errors_t = {}

function object_errors_t:__index(name)
    return self.interface:get_prop_error(name)
end

function object_errors_t:__newindex(name, value)
    if value == nil then
        self.interface:clear_prop_error(name)
    else
        self.interface:set_prop_error(name, value)
    end
end

function shared_object.set_raw_tree(raw_tree)
    g_tree = core.DevTree.new_from_raw(raw_tree)
end

function shared_object.set_raw_dbus(raw_dbus)
    local conn = core.new_from_raw(raw_dbus, false, false)
    g_dbus = sd_bus.open_user(false, false, bus_base.new(conn, {}))
end

function shared_object.create_tree()
    if g_tree then
        return g_tree
    end

    g_tree = core.DevTree.new()
    return g_tree
end

local IDX_SIGNATURE <const> = 1
function shared_object.create_shared_values(mdb_obj, raw_object)
    if not g_tree then
        g_tree = shared_object.create_tree()
    end
    local object = g_tree:register_object(mdb_obj.path)
    local iface = object:register_interface(mdb_obj.interface)
    for name, info in pairs(mdb_obj.props) do
        iface:add_p(name, info[IDX_SIGNATURE])
    end

    if raw_object then
        iface:add_p('scan_status', 'y')
        local status = raw_object.props.ScanEnabled

        raw_object.props.ScanEnabled = nil
        local new_props = setmetatable(raw_object.props, {
            __index = function(name)
                return iface:get_prop_value('scan_status')
            end,
            __newindex = function(_, name, value)
                iface:set_prop_value('scan_status', value)
            end,
        })
        new_props['scan_status'] = status
    end

    local values = setmetatable({ interface = iface, path = mdb_obj.path }, object_values_t)
    for name, value in pairs(mdb_obj.values) do
        values[name] = value
    end

    mdb_obj.values = values
    mdb_obj.error_status = setmetatable({ interface = iface }, object_errors_t)
end

local dbus_object_proxy = {}
function dbus_object_proxy:__index(name)
    local v = dbus_object_proxy[name]
    if v then
        return v
    end

    return self.shared_interface:get_prop_value(name)
end

local function get_shm_property(self, name)
    local shm_prop = self.shm_props[name]
    if shm_prop then
        if type(shm_prop.is_valid) == 'function' and not shm_prop:is_valid() then
            self.shm_props[name] = nil
            return nil
        end
        return shm_prop
    end

    local shm_tree = shm.find_tree(DBUS_SERVICE_NAME)
    if not shm_tree then
        return nil
    end

    local shm_obj = shm_tree:find_object(self.path)
    if not shm_obj then
        return nil
    end

    local shm_interface = shm_obj:find_interface(self.shared_interface.name)
    if not shm_interface then
        return nil
    end

    shm_prop = shm_interface:find_p(name)
    if not shm_prop then
        return nil
    end

    self.shm_props[name] = shm_prop
    return shm_prop
end

dbus_object_proxy.get_shm_property = get_shm_property

local function emit_dbus_properties_changed(self, changed)
    local bus = g_dbus.bus
    local emit_props1 = {}
    local emit_props2 = {}
    local emit_props = { emit_props1, emit_props2 }
    for _, prop_name in ipairs(changed) do
        local flags = changed[prop_name] or 0
        if (flags & SD_BUS_VTABLE_PROPERTY_EMITS_INVALIDATION) == 0 then
            emit_props1[#emit_props1 + 1] = {
                name = prop_name,
                value = self.shared_interface:get_prop_variant(prop_name),
            }
        else
            emit_props2[#emit_props2 + 1] = prop_name
        end
    end
    local msg = bus:new_properties_changed_signal(self.path, self.iface_name, emit_props)
    bus:notify_signal(msg)
end

dbus_object_proxy.emit_dbus_properties_changed = emit_dbus_properties_changed

local function emit_signal(self, changed)
    local ok, err = pcall(emit_dbus_properties_changed, self, changed)
    if not ok then
        log:error(
            'emit properties changed failed, path: %s, interface: %s, properties: %s, err: %s',
            self.path,
            self.iface_name,
            json.encode(changed),
            err
        )
    end
    self.changed = false
end

local function emit_properties_changed(self, name, flags)
    local changed = self.changed
    if not changed then
        changed = { name, [name] = flags }

        fork(emit_signal, self, changed)
        self.changed = changed
    elseif not changed[name] then
        changed[#changed + 1] = name
        changed[name] = flags
    end
end

dbus_object_proxy.emit_properties_changed = emit_properties_changed

function dbus_object_proxy:__newindex(name, value)
    local dbus_val = value
    local sig = self.props[name][1]
    if sig ~= 'b' and name ~= 'HealthStatus' and name ~= 'HealthStatusValidity' then
        dbus_val = binary_to_dbus_type(value, sig)
    end

    if dbus_val == self.shared_interface:get_prop_value(name) then
        return
    end

    self.shared_interface:set_prop_value(name, dbus_val)
    local flags = 0

    shm_object_lock_exec(self.object_id, function()
        local shm_prop = get_shm_property(self, name)
        if shm_prop then
            shm_prop:set_value(dbus_val)
            flags = shm_prop.flags
        end
    end)

    -- 在mdbctl设置属性值后,同步属性信号应该在此被拦截
    if (flags & SD_BUS_VTABLE_DISABLE_SHM_CACHE) == 0 then
        emit_properties_changed(self, name, flags)
    end
end

-- 发送属性变更信号,无需判断属性值是否变化
function dbus_object_proxy:emit_property_changed_signal(name)
    local flags = 0
    shm_object_lock_shared_exec(self.object_id, function()
        local shm_prop = get_shm_property(self, name)
        flags = shm_prop and shm_prop.flags or flags
    end)

    -- 在mdbctl设置属性值后,同步属性信号应该在此被拦截
    if (flags & SD_BUS_VTABLE_DISABLE_SHM_CACHE) == 0 then
        emit_properties_changed(self, name, flags)
    end
end

function dbus_object_proxy:update_shm_property(name)
    local flags = 0
    shm_object_lock_exec(self.object_id, function()
        local shm_prop = get_shm_property(self, name)
        local c_value = self.shared_interface:get_prop_value(name)
        if shm_prop and c_value ~= nil then
            shm_prop:set_value(c_value)
            flags = shm_prop.flags or flags
        end
    end)

    if (flags & SD_BUS_VTABLE_DISABLE_SHM_CACHE) == 0 then
        emit_properties_changed(self, name, flags)
    end
end

function dbus_object_proxy:set_error(name, value)
    shm_object_lock_exec(self.object_id, function()
        local shm_prop = get_shm_property(self, name)
        if not shm_prop then
            return
        end

        self.error_status[name] = value
        local flags = shm_prop.flags
        if (flags & SD_BUS_VTABLE_PROPERTY_ERROR) == 0 then
            shm_prop.flags = flags | SD_BUS_VTABLE_PROPERTY_ERROR
        end
    end)
end

function dbus_object_proxy:clear_error(name)
    self.error_status[name] = nil

    shm_object_lock_exec(self.object_id, function()
        local shm_prop = get_shm_property(self, name)
        if not shm_prop then
            return
        end

        local flags = shm_prop.flags
        if (flags & SD_BUS_VTABLE_PROPERTY_ERROR) ~= 0 then
            shm_prop.flags = flags & ~SD_BUS_VTABLE_PROPERTY_ERROR
        end
    end)
end

function dbus_object_proxy.new(mdb_obj, iface_name)
    local interface = g_tree:find_object(mdb_obj.path)
    if not interface then
        return mdb_obj
    end

    local iface = interface:register_interface(iface_name)
    if not iface then
        return mdb_obj
    end

    return setmetatable({
        mdb_obj = mdb_obj,
        error_status = setmetatable({ interface = iface }, object_errors_t),
        shared_interface = iface,
        shm_props = {},
        changed = false,
        props = mdb_obj.props,
        path = mdb_obj.path,
        object_id = allocate_object_id(mdb_obj.path),
        iface_name = iface_name,
        prop_precisions = mdb_obj.prop_precisions,
    }, dbus_object_proxy)
end

function shared_object.get_shared_object(mdb_obj, iface_name)
    if not mdb_obj.path or not mdb_obj.is_work then
        -- 主服务 mdb_obj 需要找到对应的 interface
        return mdb_obj[iface_name]
    end

    -- 工作服务的 mdb_obj 是在主服务发送过来时就将 interface 填好了
    return dbus_object_proxy.new(mdb_obj, iface_name)
end

return shared_object