#include "leak_detector.h"

#include <cstdio>
#include <cstdlib>

#include <string>
#include <vector>

#include "FileInfo.h"
#include "utils.h"
#include "errors.h"

using namespace std;

static int tmp_id = 0;
static string tmp_name = "tmp_conv_";

extern "C" int out_free_form;
extern "C" int out_line_length;

//convert through unparce
void FileInfo::convertToUniform()
{
    int old_free = out_free_form;
    int old_line = out_line_length;

    out_free_form = 1;
    out_line_length = 72;

    __spf_print(1, "covnert to uniform %s file\n", fileName.c_str());

    if (error != 0)
        printInternalError(convertFileName(__FILE__).c_str(), __LINE__);
    if (outDepPath == "")
        printInternalError(convertFileName(__FILE__).c_str(), __LINE__);

    vector<char*> filesList;
    filesList.push_back((char*)outDepPath.c_str());

    const string name = tmp_name + to_string(tmp_id++);
    SgProject* tmpProj = new SgProject(name.c_str(), filesList.data(), 1);

    if (tmpProj == NULL)
        printInternalError(convertFileName(__FILE__).c_str(), __LINE__);

    SgFile* currF = &tmpProj->file(0);

    string text = string(currF->firstStatement()->unparse());
    writeFileFromStr(fileName, text);

    out_free_form = old_free;
    out_line_length = old_line;

    InitializeTable();
}

string FileInfo::convertStyle(bool needRewrite)
{
    string tmp_text = text;

    vector<string> splited;
    splitString(tmp_text, '\n', splited);

    tmp_text = "";
    int z = 0;
    for (auto& line : splited)
    {
        if (line[0] == 'c' || line[0] == 'C' || line[0] == 'd' || line[0] == 'D' || line[0] == '*')
            line[0] = '!';

        bool needContinuation = false;
        if (line[0] != '!' && line.size() > 6)
        {
            if (line[5] != ' ' && !(line[5] > '0' && line[5] < '9')) // not label
            {
                line[5] = ' ';
                needContinuation = true;// line[5] = '&';
            }

            int p = 73;
            if (style == 1)
                p = 133;
            if (line.size() > p)
            {
                while (line[p] != '\0' && line[p] != '\n' && line[p] != '!')
                {
                    line[p] = ' ';
                    p++;
                    if (p >= line.size())
                        break;
                }
            }
        }

        if (needContinuation)
            tmp_text += "&";
        tmp_text += (z != 0 ? "\n" : "") + line;
        ++z;
    }

    if (needRewrite)
        writeFileFromStr(fileName, tmp_text);

    return tmp_text;
}
