-- 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 log = require 'mc.logging'
local singleton = require 'mc.singleton'
local c_object_manage = require 'mc.orm.object_manage'
local c_pump_object = require 'pump_object'
local c_pumps_object = require 'pumps_object'
local c_tasks = require 'mc.orm.tasks'
local ipmi = require 'ipmi'
local comp_code = ipmi.types.Cc
local _, skynet = pcall(require, 'skynet')
local client = require 'thermal_mgmt.client'
local basic_cooling_config = require 'basic_cooling_config'

local pump_service = class('Pumps')

local MAX_PWM<const> = 100
local MIN_PWM<const> = 10
local RET_ERR<const> = 1
local RET_OK<const>  = 0

function pump_service:ctor(database)
    self.db = database
    self.pump_board = {}
    self.listener = {}
end

function pump_service:set_pumps_pwm(l_pwm)
    local task_count = 0
    local co = coroutine.running()
    local resp = 0
    local create_task = function (cb)
        local task = c_tasks.get_instance():next_tick(cb)
        task_count = task_count + 1
        task.on_task_exit:on(function()
            task_count = task_count - 1
            if task_count == 0 then
                -- 所有任务处理完成，唤醒当前任务
                skynet.wakeup(co)
            end
        end)
    end

    c_pumps_object.collection:fold(function (_,obj)
        for index, pump_obj in ipairs(obj.pump_collection) do
            obj.l_pwm[index] = l_pwm [pump_obj.Id]
            l_pwm[pump_obj.Id] = nil
        end
        
        create_task(function ()
            resp = resp | obj:set_pwm(obj.l_pwm)
        end)
    end)
    skynet.wait(co)
    return resp
end


return singleton(pump_service)