#include "code.h"

#include <regex>
#include <iterator>
#include <algorithm>

namespace SELCAL {

Code::Code(std::string s) : code(s) {
    std::transform(s.begin(), s.end(), s.begin(), ::toupper);
    std::regex pattern(
        "([0-9A-Z]{" + std::to_string(KEYS_PER_GROUP) + "})"
        + GROUP_SEPARATOR +
        "([0-9A-Z]{" + std::to_string(KEYS_PER_GROUP) + "})"
    );

    std::smatch match;
    if (std::regex_match(s, match, pattern)) {
        // The first match[0] is always the entire string for a successful match
        for (std::size_t i = 1; i < match.size(); ++i) {
            std::ssub_match sub_match = match[i];
            std::string piece = sub_match.str();

            Group group;
            std::transform(piece.begin(), piece.end(), group.begin(), [](char c) {
                return static_cast<Key>(c);
            });
            groups.push_back(group);
        }
    }
    else {
        throw new std::runtime_error("Could not parse SELCAL");
    }
}

const std::vector<Group>& Code::getGroups() const {
    return groups;
}

bool Code::isValid() const {
    // TODO JMT
    return false;
}

} // SELCAL
