////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
// All rights reserved.
// Confidential and Proprietary - Qualcomm Technologies, Inc.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// THIS IS AUTO-GENERATED CODE.  PLEASE DO NOT EDIT (File bug reports against tools).
///
/// Auto-generated by: Parameter Parser V7.4.1 (8cca6579792b9fcef3bc725ff070c5ec453c7c85)
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @file  bitmlsetmanager.cpp
/// @brief Auto-generated Chromatix parameter file
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


#include "bitmlsetmanager.h"

bitmlSetManager::bitmlSetManager(
    const CHAR* const id)
    : ParameterSetManager(nullptr, 0, id, false)
{
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /// MinimumNodes
    ///
    /// @brief  Set the minimum number of scenario modes to keep in memory before unloading scenario modes.
    ///
    /// The minimum number of scenario modes to keep active before unloading modes. Used when loading binaries from
    /// a file to enable the scenario mode delay load feature (default is loaded at startup, and new scenario modes
    /// are loaded as they are entered). Switching between Snapshot and Preview mode takes up to 10 scenarios
    /// modes (depending on if the scenario modes have scenes and effects), with no links, and higher with links.
    /// to allow seamless picture taking, set the minimum to at least 10. The default value is 17 to account for
    /// linked modes. Smaller values will increase memory usage efficiency at the cost of scenario mode switching
    /// latency. To use a different value, set the ParameterParser --MinNodes <number> command line option when
    /// generating source (the s command). Setting this value to 0 disables auto scenario mode unloading.
    /// Call the UnloadMode function to manually unload a scenario mode. Calling UnloadMode directly will ignore
    /// Module reference counts, unload all modules and set their reference counts to 0.  Do not call UnloadMode
    /// unless you are certain no modules are referenced within the mode.
    ///
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    MinimumModes  = 17;
    DelayLoad     = true;
    LogError      = true;
    LogWarning    = true;
    LogDebug      = true;
    SimulatorMode = false;
    Main          = nullptr;

    AddDefaultModule(PARAMETER_NEW camxbitmlconfig::BITMLConfigTypeClass("BITMLConfig"));

    PARAMETER_LOG_DEBUG(this, "bitmlSetManager constructed: %s\n", VERSION);
};

bitmlSetManager::bitmlSetManager(
    bitmlSetManager * main,
    BYTE modeTableIndex)
    : ParameterSetManager(main, modeTableIndex, nullptr, false)
{
    Main = main;
    if (main == nullptr)
    {
        PARAMETER_LOG_ERROR(this, "%s called with null main parameter\n", __FUNCTION__);
    }
}

bitmlSetManager::~bitmlSetManager()
{
    PARAMETER_LOG_DEBUG(this, "bitmlSetManager deleting\n");

    std::unordered_map<UINT64, DefaultModule*>::iterator typeIter = DefaultModuleMapHash.begin();
    while (typeIter != DefaultModuleMapHash.end())
    {
        PARAMETER_DELETE typeIter->second;
        typeIter++;
    }
    DefaultModuleMapHash.clear();
    Main = nullptr;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// CreateSetManager
///
/// @brief Creates a set manager for the specified mode table index
///
/// @param modeTableIndex Mode table index
///
/// @return A new set manager object with the mode table index set modeTableIndex, or null if modeTableIndex is >=
///         the number of available mode tables
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bitmlSetManager* bitmlSetManager::CreateSetManager(
    BYTE modeTableIndex)
{
    if (Main != nullptr)
    {
        return GetMainSetManager()->CreateSetManager(modeTableIndex);
    }

    bitmlSetManager* result = nullptr;
    if (modeTableIndex < GetMainSetManager()->m_modeTables.Count())
    {
        result = PARAMETER_NEW bitmlSetManager(GetMainSetManager(), modeTableIndex);
    }
    else
    {
        PARAMETER_LOG_ERROR(this, "%s called mode table index (%u) >= mode table count (%u)\n", __FUNCTION__,
            modeTableIndex, m_modeTables.Count());
    }

    return result;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// CreateSetManager
///
/// @brief Creates a set manager for the specified mode table name
///
/// @param modeTableName Mode table name
///
/// @return A new set manager object with the mode table index set to the index for the specified mode table name, or
///         null if the mode table name is not found
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bitmlSetManager* bitmlSetManager::CreateSetManager(
    const CHAR* const modeTableName)
{
    if (Main != nullptr)
    {
        return GetMainSetManager()->CreateSetManager(modeTableName);
    }

    bitmlSetManager* result = nullptr;
    if (modeTableName != nullptr)
    {
        bitmlSetManager* main = GetMainSetManager();
        UINT32            count = main->m_modeTables.Count();
        for (UINT32 i = 0; result == nullptr && i < count; i++)
        {
            if (main->m_modeTables[i]->Name != nullptr && PARAMETER_STRCMP(main->m_modeTables[i]->Name, modeTableName) == 0)
            {
                result = PARAMETER_NEW bitmlSetManager(main, (BYTE)i);
            }
        }
        if (result == nullptr)
        {
            PARAMETER_LOG_ERROR(this, "%s unable to find mode table %s\n", __FUNCTION__,
                modeTableName);
        }
    }
    else
    {

    }

    return result;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// GetMainSetManager
///
/// @brief Returns the main set manager, this is the set manager used for all interactions
///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bitmlSetManager* bitmlSetManager::GetMainSetManager()
{
    if (Main != nullptr)
    {
        return Main->GetMainSetManager();
    }
    else
    {
        return this;
    }
}

void bitmlSetManager::AddDefaultModule(ParameterModule* module)
{
    if (Main == nullptr && module != nullptr)
    {
        DefaultModule* defModule = PARAMETER_NEW DefaultModule(module);
        DefaultModuleMapHash[module->NameHash] = defModule;
    }
    else
    {
        SetError("AddDefaultModule called on a derived set manager object");
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// UpdateBinaryParameters
///
/// @brief Replaces exising parameters with the ones in a buffer. LoadBinaryParameters must be called first
///
/// @param buffer   Binary parameter buffer
/// @param length   Length of the binary parameter buffer
///
/// @return Node
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#ifdef PARAMETER_UPDATE_FUNTION
#ifdef __ZEPHYR__
#error "The update function is not compatible with Zephyr OS, remove --update from the Parameter Parser command line"
#endif
bool bitmlSetManager::UpdateBinaryParameters(
    UINT8* const buffer,
    const SIZE_T length)
{
    if (Main != nullptr)
    {
        return GetMainSetManager()->UpdateBinaryParameters(buffer, length);
    }

    bool result = Valid;

    if (result)
    {
        PARAMETER_LOG_DEBUG(this, "%s: Replacing with parameter from a buffer\n", __FUNCTION__);

#ifdef PARAMETER_USE_MUTEX
        const std::unique_lock<std::shared_mutex> ulock(UpdateMutex); // Unique LOCK
#endif
        if (IsFileMode())
        {
            result = ReloadBinaryParameters(true);
        }

        if (result)
        {
            bitmlSetManager* update = PARAMETER_NEW bitmlSetManager();

            if (update->LoadBinaryParameters(buffer, length))
            {
                (void)UpdateParameters(update);
                result = true;
            }
            else
            {
                SetError("UpdateBinaryParameters failed to load parameters");
            }
            m_updateSM.push_back((ParameterSetManager*)update);
        }
        else
        {
            SetError("UpdateBinaryParameters failed to reload parameters in buffer mode");
        }
    }
    else
    {
        SetError("UpdateBinaryParameters failed, original parameter load is invalid");
    }

    return result;
}
#else
bool bitmlSetManager::UpdateBinaryParameters(
    UINT8* const,
    const SIZE_T)
{
    PARAMETER_LOG_ERROR(this, "%s not available.  To enable, add --update when generating parser utility code\n", __FUNCTION__);
    return false;
}
#endif

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// SaveAndClearModules
///
/// @brief  Saves all current modules to the m_replaced list to prevent accessing deleted memory
///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void bitmlSetManager::SaveAndClearModules()
{
    if (Main != nullptr)
    {
        return GetMainSetManager()->SaveAndClearModules();
    }

    std::unordered_map<UINT64, DefaultModule*>::iterator hashIter = DefaultModuleMapHash.begin();
    while (hashIter != DefaultModuleMapHash.end())
    {
        SaveAndClearModule(hashIter->second);
        hashIter++;
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// SaveAndClearModules
///
/// @brief  Saves module to the m_replaced list to prevent accessing deleted memory
///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void bitmlSetManager::SaveAndClearModule(DefaultModule* const module)
{
    if (Main != nullptr)
    {
        return GetMainSetManager()->SaveAndClearModule(module);
    }

    if (module != nullptr)
    {
        ModuleLink* link = module->FirstModule;
        while (link != nullptr)
        {
            ModuleLink* const next = link->Next;
            m_replaced.push_back(link->Module);
            link->Module = nullptr;
            link->Next   = nullptr;
            PARAMETER_DELETE link;
            link = next;

        }
        module->FirstModule = nullptr;
        module->LastModule  = nullptr;
    }
}

camxbitmlconfig::BITMLConfigType* bitmlSetManager::GetModule_BITMLConfig(
    const TuningMode* const modeBranch,
    UINT32 const modeCount,
    camxbitmlconfig::BITMLConfigType* const release)
{
    ParameterModule* const pModule = GetModule("BITMLConfig",
        modeBranch, modeCount, (ParameterModule*)(camxbitmlconfig::BITMLConfigTypeClass*)release);

    return (camxbitmlconfig::BITMLConfigType*)(camxbitmlconfig::BITMLConfigTypeClass*)pModule;
}

