#include "RunDataLite.h"
#include <regex>
#include <iostream>

RunDataLite::RunDataLite(std::string filePath): fileStream(filePath), filePath(filePath)
{
    std::string file = filePath.substr(filePath.find_last_of("/\\") + 1);
    name = file.substr(0, file.rfind("."));
    if (!fileStream.is_open())
    {
        //Cant open file
        badFileFlag = true;
        std::cout << "Cannot open File.";
        return;
    }
    /* Start extracting */
    while (fileStream.peek() != EOF) {
        std::string buffer;
        getLine(buffer);
        SolutionPointData sol;

        std::regex regexIter("i:([\\+\\-]?\\d+)");
        std::regex regexObjectiveFunction("of:([\\+\\-]?\\d+\\.\\d+(?:E[\\+\\-]\\d+)?)");
        std::smatch match;
        if (!std::regex_search(buffer, match, regexIter)) {
           std::cout << "Bad formatatted Line[" << actualLine << "].";
           std::cout << "Failed to matched:";
           std::cout << buffer;
            return;
        }
        sol.iteration = std::stoi(match[1]);
        if (!std::regex_search(buffer, match, regexObjectiveFunction)) {
           std::cout << "Bad formatatted Line[" << actualLine << "].";
           std::cout << "Failed to matched:";
           std::cout << buffer;
            return;
        }
        sol.objectiveFunction = std::stod(match[1]);
        std::regex regexParticleNumber("pN:([\\+\\-]?\\d+)");
        if (!std::regex_search(buffer, match, regexParticleNumber)) {
           std::cout << "Bad formatatted Line[" << actualLine << "].";
           std::cout << "Failed to matched:";
           std::cout << buffer;
            return;
        }
        sol.particleNumber = std::stoi(match[1]);
        std::regex regexBitVec("b:([01]+)");
        if (!std::regex_search(buffer, match, regexBitVec)) {
           std::cout << "Bad formatatted Line[" << actualLine << "].";
           std::cout << "Failed to matched:";
           std::cout << buffer;
            return;
        }
        sol.bitVec.resize(match[1].length());
        int count = 0;
        std::string str = match[1];
        for (std::string::size_type i = 0; i < str.size(); ++i) {
            sol.bitVec[i] = (str[i] == '1');
        }
        solutionVec.push_back(sol);
    }
    fileStream.close();
}

bool RunDataLite::badFile()
{
    return badFileFlag;
}

void RunDataLite::getLine(std::string& bufferString)
{
    std::getline(fileStream, bufferString);
    actualLine++;
}

