
#include "import_mentor.hpp"
#include "system/parts.hpp"
#include "system/pins.hpp"

#include <string>
#include <regex>

enum class State {
    NO_PART,
    IS_PART,
};

ImportMentor::ImportMentor(): ImportBase() {

}

ImportMentor::~ImportMentor() {
    ImportBase::~ImportBase();
}

void ImportMentor::parse(std::fstream lines) {
    std::string line;
    auto state = State::NO_PART;
    const std::regex name_regex("\\'([^\\']*)\\'");
    const std::regex part_regex("^COMP:");
    const std::regex pin_regex("^Explicit Pin:");

    while (std::getline(lines, line))
    {
        Part *prt = nullptr;
        std::smatch name_match;
        bool is_name_match = std::regex_match(line, name_match, part_regex);
        bool is_part_match = std::regex_match(line, part_regex);
        bool is_pin_match = std::regex_match(line, pin_regex);
        switch (state)
        {
        case State::NO_PART:
            if (is_part_match) {
                if (is_name_match) {
                    prt = new Part(name_match[0]);
                    state = State::IS_PART;
                }
            }
            break;

        default:
            if (is_part_match) {
                if (is_name_match) {
                    prts->add(*prt);
                    prt = new Part(name_match[0]);
                }
            }
            else if (is_pin_match)
            {
                if (is_name_match) {
                    auto pin = new Pin(name_match[0]);
                    prt->add(*pin);
                }
            }
            break;
        }
        if (state == State::IS_PART) {
            prts->add(*prt);
        }
    }
}