/*Copyright (C) 2010-2023 Duncan Deveaux

This file is part of Hikou no mizu.

Hikou no mizu is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Hikou no mizu is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Hikou no mizu.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "ArgumentParser.hpp"

namespace
{
    void log_unexpectedOption(const std::string &optionName)
    {
        Log::err(Format::format("Unknown option: {}", optionName));
    }

    void log_missingValue(const std::string &optionName)
    {
        Log::err(Format::format("Missing value for the option: {}",
                                optionName));
    }

    /// Browse the command line options and prepare them for parsing by
    /// breaking down the --long-option=value arguments to two separate entries
    std::vector<std::string> prepareOptions(int argc, char **argv)
    {
        std::vector<std::string> options;
        for (int i = 1; i < argc && argv[i] != nullptr; i++)
        {
            std::string option(argv[i]);
            std::size_t delimiter = option.find_last_of('=');

            if (delimiter == std::string::npos && !option.empty())
                options.push_back(std::move(option));
            else
            {
                std::string argument = option.substr(0, delimiter);
                std::string value = option.substr(delimiter+1);

                if (!argument.empty()) options.push_back(std::move(argument));
                if (!value.empty()) options.push_back(std::move(value));
            }
        }

        return options;
    }
}

void ArgumentParser::addShortOption(char option, bool expectValue)
{
    m_expectedOptions[{'-', option}] = expectValue;
}

void ArgumentParser::addLongOption(const std::string &option, bool expectValue)
{
    m_expectedOptions["--" + option] = expectValue;
}

void ArgumentParser::addOption(char shortName, const std::string &longName,
                               bool expectValue)
{
    addShortOption(shortName, expectValue);
    addLongOption(longName, expectValue);
}

ParsedOptions ArgumentParser::parse(int argc, char **argv) const
{
    ParsedOptions parsed;
    if (argc < 2)
        return parsed;

    /// Whether an argument is expected, otherwise, a value
    /// associated with the previously read argument is expected
    bool expectingArgument = true;

    std::vector<std::string> options = prepareOptions(argc, argv);
    for (std::string &data : options)
    {
        if (expectingArgument)
        {
            if (data.front() != '-' || m_expectedOptions.count(data) == 0)
            {
                log_unexpectedOption(data);
                parsed.hadError = true;
                return parsed;
            }
            else if (!parsed.hasOption(data))
            {
                expectingArgument = !m_expectedOptions.at(data);
                parsed.options.emplace_back(std::move(data));
            }
        }
        else if (!parsed.options.empty())
        {
            if (data.front() != '-')
            {
                parsed.options.back().value = std::move(data);
                expectingArgument = true; //Expect the next argument
            }
            else
            {
                log_missingValue(parsed.options.back().name);
                parsed.hadError = true;
                parsed.options.pop_back();
                return parsed;
            }
        }
    }

    //Terminated without providing the expected value
    if (!expectingArgument && !parsed.options.empty())
    {
        log_missingValue(parsed.options.back().name);
        parsed.hadError = true;
        parsed.options.pop_back();
    }

    return parsed;
}
