/*
 * Copyright (c) 2018-2020, NVIDIA CORPORATION.  All rights reserved. All
 * information contained herein is proprietary and confidential to NVIDIA
 * Corporation.  Any use, reproduction, or disclosure without the written
 * permission of NVIDIA Corporation is prohibited.
 */

#include "CNvMEEPROM.hpp"

namespace nvsipl
{

SIPLStatus CNvMEEPROM::SetConfig(const EEPROMInfo *eepromInfo, DeviceParams *params)
{
    m_oDeviceParams = *params;

    if (!m_oDeviceParams.bEnableSimulator and !m_oDeviceParams.bSlave) {
        m_nativeI2CAddr =  eepromInfo->i2cAddress;
        m_oDeviceParams.pI2CAddrMgr->RegisterNativeI2CAddr(m_nativeI2CAddr);
    }

    m_eState = CDI_DEVICE_CONFIG_SET;

    return NVSIPL_STATUS_OK;
}

SIPLStatus CNvMEEPROM::ReadData(const std::uint16_t address,
                                const std::uint32_t length,
                                std::uint8_t * const buffer)
{
    DevBlkCDIDevice *dev = nullptr;
    NvMediaStatus nvmerr = NVMEDIA_STATUS_OK;

    if (length == 0UL) {
        LOG_INFO("Invalid read length %u\n", length);
        return NVSIPL_STATUS_BAD_ARGUMENT;
    } else if (buffer == nullptr) {
        LOG_INFO("Invalid buffer\n");
        return NVSIPL_STATUS_BAD_ARGUMENT;
    }

    if (m_pCDIDriver == nullptr) {
        LOG_ERR("EEPROM device is not initialize\nd");
        return NVSIPL_STATUS_INVALID_STATE;
    }

    dev = GetCDIDeviceHandle();
    if (dev == nullptr) {
        LOG_ERR("Failed to retrieve CDI device handle\n");
        return NVSIPL_STATUS_ERROR;
    }

    nvmerr = m_pCDIDriver->ReadRegister(dev, 0, address, length, buffer);
    if (nvmerr != NVMEDIA_STATUS_OK) {
        LOG_ERR("Failed to perform device read\n");
        return NVSIPL_STATUS_ERROR;
    }

    return NVSIPL_STATUS_OK;
}

#if !NV_IS_SAFETY
SIPLStatus CNvMEEPROM::WriteData(const std::uint16_t address,
                                 const std::uint32_t length,
                                 std::uint8_t * const buffer)
{
    DevBlkCDIDevice *dev = nullptr;
    NvMediaStatus nvmerr = NVMEDIA_STATUS_OK;

    if (length == 0UL) {
        LOG_INFO("Invalid write length %u\n", length);
        return NVSIPL_STATUS_BAD_ARGUMENT;
    } else if (buffer == nullptr) {
        LOG_INFO("Invalid buffer\n");
        return NVSIPL_STATUS_BAD_ARGUMENT;
    }

    if (m_pCDIDriver == nullptr) {
        LOG_ERR("EEPROM device is not initialize\nd");
        return NVSIPL_STATUS_INVALID_STATE;
    }

    dev = GetCDIDeviceHandle();
    if (dev == nullptr) {
        LOG_ERR("Failed to retrieve CDI device handle\n");
        return NVSIPL_STATUS_ERROR;
    }

    nvmerr = m_pCDIDriver->WriteRegister(dev, 0, address, length, buffer);
    if (nvmerr != NVMEDIA_STATUS_OK) {
        LOG_ERR("Failed to perform device write\n");
        return NVSIPL_STATUS_ERROR;
    }

    return NVSIPL_STATUS_OK;
}
#endif // !NV_IS_SAFETY

} // end of nvsipl
