/*
 * IdealIRC - Internet Relay Chat client
 * Copyright (C) 2019  Tom-Andre Barstad
 *
 * This program 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 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#include "InputHandler.h"
#include "IWin/IWin.h"
#include "ICommand/ICommand.h"
#include "ICommand/Commands.h"
#include "IRC.h"
#include "ConfigMgr.h"
#include "IRCClient/IRCMember.h"
#include "IRCClient/IRCChannel.h"
#include <QDebug>

InputHandler::InputHandler(IRC& connection_)
	: connection(connection_)
	, cmdHndl(connection_)
{}

void InputHandler::parse(IWin& sender, const QString& text, bool handleCommand)
{
	if (text.isEmpty())
		return;

	if (text[0] == '/' && handleCommand)
		cmdHndl.parse(text);
	else {
		if (sender.getType() == IWin::Type::Status) {
			sender.print(PrintType::ProgramInfo, "You're not in a chat window!");
			return;
		}
		else {
			const std::string target = sender.getButtonText().toStdString();
			std::string me = connection.getNickname();
			connection.command(Command::IRC::PRIVMSG, { target }, text.toStdString());

			if (ConfigMgr::instance().common("ShowModeInMessage") == "1") do {
				const auto& myChannels = connection.channels();
				auto chanIt = std::find_if(myChannels.begin(), myChannels.end(),
					[&target](std::shared_ptr<IRCChannel> ptr) {
						return target == ptr->name();
					});

				if (chanIt == myChannels.end()) {
					qWarning() << "Could not find channel '" << target.c_str() << "' internally, although it seems we're on it anyway.";
					break;
				}

				const auto& member = (*chanIt)->getMember(me)->get();
				const auto prefixes = connection.toMemberPrefix(member.modes());
				if (!prefixes.empty())
					me.insert(me.begin(), prefixes[0]);
			} while(0);

			sender.print(PrintType::OwnText, QStringLiteral("<%1> %2")
												.arg(me.c_str())
												.arg(text));
		}
	}
}

void InputHandler::parseCommand(const QString& text)
{
	cmdHndl.parse(text);
}