/*
PolyGun

Copyright (c) 2023 mrkubax10 <mrkubax10@onet.pl>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#include "server/command_parser.hpp"

#include <iostream>

#include "server/server.hpp"
#include "common/logger.hpp"

using namespace polygun::server;

CommandParser::CommandParser(Server& server) :
	m_server(server)
{}

void CommandParser::parse(const std::string& line) {
	std::vector<std::string> tokens;
	std::string current_token;
	bool inside_quotes = false;
	bool escaped = false;
	for(size_t i = 0; i<line.length(); i++) {
		char ch = line[i];
		switch(ch) {
		case '\\':
			if(!escaped) {
				escaped = true;
				continue;
			}
		case '"':
			if(!escaped) {
				inside_quotes = !inside_quotes;
				continue;
			}
			break;
		case ' ':
			if(!current_token.empty() && !inside_quotes) {
				tokens.push_back(current_token);
				current_token.clear();
				continue;
			}
			break;
		}
		current_token+=ch;
		if(escaped)
			escaped = false;
	}
	if(!current_token.empty())
		tokens.push_back(current_token);

	if(tokens.empty())
		return;

	const std::string& command = tokens[0];
	if(command=="quit")
		m_server.m_running->store(false);
	else if(command=="help")
		handle_help_command();
	else
		LOG_ERROR("Unknown command '%s'", command.c_str());
}

void CommandParser::handle_help_command() {
	std::cout<<"Available commands: "<<std::endl;
	std::cout<<" quit - shutdowns server"<<std::endl;
	std::cout<<" help - shows this message"<<std::endl;
}
