-- 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 end_time = ReqBody.SelEndTime
if end_time == nil then
    return true
end

local function is_characters_valid()
    local _, count = string.gsub(end_time, "-", "")
    if count ~= 2 then
        return false
    end
    _, count = string.gsub(end_time, ":", "")
    if count ~= 2 then
        return false
    end
    if string.match(end_time, '[^%d%-%:%s]+') then
        return false
    end
    return true
end

local function is_exist(year, month, day, hour, min, sec)
    if year and month and day and hour and min and sec then
        return true
    end
    return false
end

local function is_value_valid(year, month, day, hour, min, sec)
    if month > 12 or month < 1 then
        return false
    end
    if day > 31 or day < 1 then
        return false
    end
    if hour > 23 or hour < 0 then
        return false
    end
    if min > 59 or min < 0 then
        return false
    end
    if sec > 59 or sec < 0 then
        return false
    end
    if year > 2100 or year < 2000 then
        return false
    end
    return true
end

local function is_valid_date(date_str)
    if not is_characters_valid() then
        return false
    end
    local pattern = "(%d%d%d%d)-(%d%d)-(%d%d) (%d%d):(%d%d):(%d%d)"
    local year, month, day, hour, min, sec = date_str:match(pattern)
    if is_exist(year, month, day, hour, min, sec) then
        year, month, day, hour, min, sec = tonumber(year), tonumber(month), tonumber(day),
            tonumber(hour), tonumber(min), tonumber(sec)
        if not is_value_valid(year, month, day, hour, min, sec) then
            return false
        end
        return true
    end
    return false
end

local is_valid = is_valid_date(end_time)

if not is_valid then
    local err = base_messages.ActionParameterValueFormatError(end_time, 'SelEndTime',
        'Oem/{{OemIdentifier}}/LogService.QuerySelLogEntries')
    error(err)
end