/*
 * Copyright (c) 2018-2019, 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 <iterator>
#include <fstream>
#include "platform/CNvMPlatform.hpp"
#include "trace/CNvMTrace.hpp"

namespace nvsipl
{

CNvMPlatform::CNvMPlatform()
{
    m_bInitialized = false;

    LOG_INFO("\n");

#if defined(NVMEDIA_QNX)
    std::string sTargetModelNode = "/dev/nvdt/model";
#else
    std::string sTargetModelNode = "/proc/device-tree/model";
#endif

    std::ifstream fs;
    fs.open(sTargetModelNode, std::ifstream::in);
    if (!fs.is_open()) {
        LOG_ERR("CNvMPlatform: cannot open board node %s \n", sTargetModelNode.c_str());
        return;
    }

    // Read the file in to the string.
    std::string nodeString;
    fs >> nodeString;
    LOG_INFO("CNvMPlatform: Target model node is %s \n", nodeString.c_str());

    fs.close();

    m_bInitialized = true;

    // Set default configuration.
    m_oConfiguration.deserName = "MAX96712";
    m_oConfiguration.fps = 30.0f;
    m_oConfiguration.dutyCycle = 0.25f;

    //! Find board name using node string. Override any config information
    if (strncmp(nodeString.c_str(), "e3550_t194a", nodeString.size()) == 0) {
        m_oConfiguration.boardName = "ddpx-a";
    } else if (strncmp(nodeString.c_str(), "e3550_t194b", nodeString.size()) == 0) {
        m_oConfiguration.boardName = "ddpx-b";
    } else if (strncmp(nodeString.c_str(), "p2888_t194", nodeString.size()) == 0) {
        m_oConfiguration.boardName = "ddpx-c";
    } else if (strncmp(nodeString.c_str(), "p3479_t194", nodeString.size()) == 0) {
        m_oConfiguration.boardName = "p3479";
    } else if (strncmp(nodeString.c_str(), "p3570_t194a", nodeString.size()) == 0) {
        m_oConfiguration.boardName = "p3570-a";
    } else if (strncmp(nodeString.c_str(), "p3570_t194b", nodeString.size()) == 0) {
        m_oConfiguration.boardName = "p3570-b";
    } else {
        LOG_ERR("CNvMPlatform: Could not detect board matching node:%s\n", nodeString.c_str());
        m_bInitialized = false;
    }
}

CNvMPlatform::~CNvMPlatform() {
    LOG_INFO("\n");
    m_bInitialized = false;
}

CNvMPlatform* CNvMPlatform::GetInstance()
{
    static CNvMPlatform m_oPlatform;

    if (!m_oPlatform.m_bInitialized) {
        LOG_ERR("Failed to initialize\n");
    }

    return &m_oPlatform;
}

} // end of namespace nvsipl
