-- 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.

-- eeprom 模型
-- 支持offsetwidth: 1, 2, 4
-- 数据大小：任意
-- 支持生成指定大小的数据文件，默认size为1024
local Eeprom = {
    offset_width = 1,
    size = 1024
}

local log = require "log"
local cjson = require "cjson"
local CommonI2c = require "protocol.CommonI2c"
local BinParser = require "data.BinParser"

function Eeprom:new(o, offset_width, size)
    o = o or {}
    setmetatable(o, self)
    self.__index = self
    self.offset_width = offset_width
    self.size = size
    return o
end

local EepromParser = {
    prot_parser = {},
    data_parser = {},
}

function EepromParser:new(o, prot_parser, data_parser)
    o = o or {}
    setmetatable(o, self)
    self.__index = self
    self.prot_parser = prot_parser
    self.data_parser = data_parser
    return o
end

function EepromParser:read_data(length)
    local offset = self.prot_parser:parse_offset()
    return self.data_parser:read_data(offset, length)
end

function EepromParser:write_data()
    local offset = self.prot_parser:parse_offset()
    local data = self.prot_parser:parse_data()

    log:print(LOG_ERROR, "eeprom write_data offset is %d", offset)
    log:print(LOG_ERROR, "eeprom write_data data is %s", cjson.encode(data))

    self.data_parser:write_data(offset, data)
end

function Eeprom:read(tx_buffer, length, filename)
    if type(tx_buffer) ~= "table" or #tx_buffer < 2 then    -- 2: 读命令时传输数据的最小长度
        log:print(LOG_ERROR, "tx_buffer length(%d) error", #tx_buffer)
        return
    end
    local common_i2c = CommonI2c:new(nil, tx_buffer, self.offset_width)
    local bin_parser = BinParser:new(nil, filename, self.size)

    local eeprom_parser = EepromParser:new(nil, common_i2c, bin_parser)
    return eeprom_parser:read_data(length)
end

function Eeprom:write(tx_buffer, filename)
    if type(tx_buffer) ~= "table" or #tx_buffer < 3 then    -- 3: 写命令时传输数据的最小长度
        log:print(LOG_ERROR, "tx_buffer length(%d) error", #tx_buffer)
        return
    end

    log:print(LOG_ERROR, "write eeprom get tx_buffer is %s", cjson.encode(tx_buffer))
    local common_i2c = CommonI2c:new(nil, tx_buffer, self.offset_width)
    local bin_parser = BinParser:new(nil, filename, self.size)

    local eeprom_parser = EepromParser:new(nil, common_i2c, bin_parser)
    eeprom_parser:write_data()
end

return Eeprom
