-- 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 sutils = require 'session.infrastructure.session_utils'
local log = require 'mc.logging'
local vos = require 'utils.vos'
local Session = class()

local role_map = {
    ['0'] = "NoAccess",
    ['2'] = "CommonUser",
    ['3'] = "Operator",
    ['4'] = "Administrator",
    ['5'] = "CustomRole1",
    ['6'] = "CustomRole2",
    ['7'] = "CustomRole3",
    ['8'] = "CustomRole4"
}

local function convert_role_id(role_id)
    return { role_map[role_id] }
end

local privileges = {
    "UserMgmt",
    "BasicSetting",
    "KVMMgmt",
    "VMMMgmt",
    "SecurityMgmt",
    "PowerMgmt",
    "DiagnoseMgmt",
    "ReadOnly",
    "ConfigureSelf"
}

local function convert_privileges(currnet_privileges)
    local session_privileges = {}
    for _, privilege in pairs(privileges) do
        if string.find(currnet_privileges, privilege) then
            table.insert(session_privileges, privilege)
        end
    end
    return session_privileges
end
function Session:ctor(account_info, password, ip, session_type)
    self.account_info = account_info
    self.client_origin_ip_address = ip
    self.token = sutils.generate_token()
    self.csrf_token = sutils.generate_token()
    self.session_id = sutils.generate_session_id(self.token)
    self.created_time = os.date('%c')
    self.oem_session_type = 0
    self.account_password = password
    self.session_type = session_type
    self.user_name = account_info.AccountData.UserName
    self.last_login_ip = account_info.AccountData.LastLoginIP
    self.last_login_time = account_info.AccountData.LastLoginTime
    self.auth_type = 0
    self.role_id = convert_role_id(account_info.AccountData.RoleId)
    self.privileges = convert_privileges(account_info.AccountData.current_privileges)
    self.account_id = account_info.AccountData.Id
    self.browser_type = 0
    self.session_last_renew_time = vos.vos_get_cur_time_stamp()
end

function Session:renew_session_timeout()
    self.session_last_renew_time = vos.vos_get_cur_time_stamp()
end

function Session:check_privileges(required_privilege)
    local privilege_check =false
    for _,v in pairs(self.privileges) do
        if v == required_privilege then
            privilege_check = true
        end
    end
    return privilege_check
end

return Session
