#include "leak_detector.h"

#include <set>
#include <map>
#include <string>

#include "SgUtils.h"
#include "uniq_name_creator.h"
#include "resolve_par_reg_conflicts.h"

using namespace::std;

static const string COMMON_ARRAY_SUFFIX = "_c";
static const string COMMON_BLOCK_SUFFIX = "_r";

void UniqueNameCreator::GetSymbolsRec(SgExpression* exp, set<string>& add_to)
{
    if (!exp)
        return;

    if (isArrayRef(exp) && exp->symbol() && exp->symbol()->identifier())
        add_to.emplace(exp->symbol()->identifier());

    GetSymbolsRec(exp->lhs(), add_to);
    GetSymbolsRec(exp->rhs(), add_to);
}

void UniqueNameCreator::FillDeclarations()
{
    allDeclarations.clear();
    auto* file_before = current_file;

    for (const auto& by_file : funcInfo)
    {
        if (SgFile::switchToFile(by_file.first) != -1)
        {
            for (const auto* by_func : by_file.second)
            {
                SgStatement* st = by_func->funcPointer;

                if (st)
                    st = st->lexNext();

                while (st)
                {
                    for (int i = 0; i < 3; i++)
                        GetSymbolsRec(st->expr(i), allDeclarations);

                    st = st->lexNext();
                }
            }
        }
        else
            printInternalError(convertFileName(__FILE__).c_str(), __LINE__);
    }

    SgFile::switchToFile(file_before->filename());
    declarationsAnalyzed = true;
}

void UniqueNameCreator::GetUniqueName(DIST::Array* array, string& array_name, string& common_block_name)
{
    auto varsOnPos = getArraySynonyms(array);
    if (!varsOnPos.size())
        printInternalError(convertFileName(__FILE__).c_str(), __LINE__);

    auto array_plain_name = varsOnPos[0]->getName();

    auto it = generatedNames.find(array);
    if (it != generatedNames.end())
    {
        array_name.assign(it->second.first);
        common_block_name.assign(it->second.second);
        return;
    }

    if (!declarationsAnalyzed)
        FillDeclarations();

    int v = 1;
    auto created_array_name = array_plain_name + COMMON_ARRAY_SUFFIX;
    auto created_common_name = array_plain_name + COMMON_BLOCK_SUFFIX;

    while (allDeclarations.find(created_array_name) != allDeclarations.end() ||
        allDeclarations.find(created_common_name) != allDeclarations.end())
    {
        created_array_name = array_plain_name + "_v" + std::to_string(v) + COMMON_ARRAY_SUFFIX;
        created_common_name = array_plain_name + "_v" + std::to_string(v) + COMMON_BLOCK_SUFFIX;
        v++;
    }

    allDeclarations.insert(created_array_name);
    allDeclarations.insert(created_common_name);
    generatedNames.emplace(array, std::make_pair(created_array_name, created_common_name));

    array_name.assign(created_array_name);
    common_block_name.assign(created_common_name);
}
