-- Copyright (c) 2024 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 class = require 'mc.class'
local singleton = require 'mc.singleton'
local c_valve_object = require 'valve_object'
local ipmi = require 'ipmi'
local comp_code = ipmi.types.Cc

local valve_service = class()


function valve_service:ctor(database, bus)
    self.db = database
    self.bus = bus
end

function valve_service:get_valve_opening_degree(valve_id)
    local valve_obj = c_valve_object.collection:find({Id = valve_id})
    if valve_obj ~= nil then
        return valve_obj:get_opening_degree(), comp_code.Success
    end
    return 0, comp_code.InvalidCommand
end

function valve_service:get_valve_standard_opening_degree(valve_id)
    local valve_obj = c_valve_object.collection:find({Id = valve_id})
    if valve_obj ~= nil then
        return valve_obj:get_standard_opening_degree(), comp_code.Success
    end
    return 0, comp_code.InvalidCommand
end

function valve_service:set_valve_opening_degree(ctx, valve_id, degree)
    local valve_obj = c_valve_object.collection:find({Id = valve_id})
    local ret

    if valve_obj == nil then
        return comp_code.InvalidCommand
    end

    ret = valve_obj:set_opening_degree(degree)

    if ret then
        ipmi.ipmi_operation_log(ctx, 'thermal_mgmt',
            'Successfully started adjusting the valve angle to %.1f%% of its full-open degrees', degree / 10)
        return comp_code.Success
    end

    ipmi.ipmi_operation_log(ctx, 'thermal_mgmt',
        'Failed to adjust the valve angle to %.1f%% of its full-open degrees', degree / 10)

    return comp_code.ParmOutOfRange
end

return singleton(valve_service)
