-- 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 log = require 'mc.logging'
local custom_messages = require 'messages.custom'
local m = {}

function m.get_ntpservers(input)
    if input[5] == 'Static' and input[1] ~= 'Static' then
        return
    end
    if input[5] == 'DHCP' and input[1] == 'Static' then
        return
    end
    local servers = {}
    servers[#servers + 1] = input[2]
    servers[#servers + 1] = input[3]
    for _, ser in pairs(input[4]) do
        servers[#servers + 1] = ser
    end
    return servers
end

function m.set_ntpservers(input)
    local servers = input[1]
    if input[2] ~= 'Static' then
        log:error('Failed to set the NTP servers because NTPMode is not Static.')
        local err = custom_messages.PropertyModificationNotSupported('NTPServers')
        err.RelatedProperties = {'#/NTP/NTPServers'}
        error(err)
    end
    if #servers > input[3] then
        log:error('the number(%s) of requested NTP servers is not equal to NTPServerCount(%s)',
            #servers, input[3])
        local err = base_messages.PropertyValueFormatError(table.concat(servers, ','), 'NTPServers')
        err.RelatedProperties = {'#/NTP/NTPServers'}
        error(err)
    end
    local prefer = servers[1] or ''
    local alte = servers[2] or ''
    local extra = {}
    if #servers >= 3 then
        table.move(servers, 3, #servers, 1, extra)
    end

    return { prefer, alte, extra }
end

return m
