#include "AccountStatus.hpp"
#include <string>
#include <cstdlib>
#include <iostream>
#include "PrintFile.hpp"
#include "common.hpp"
#include "ExecCommand.hpp"
#include "json.hpp"
#include "base64.h"
#include "cleanHtml.h"
#include <sstream>

using namespace std;
void AccountHelp(bool isRussian)
{
	if (isRussian)
	{
		std::cout <<
			R"(
Использование: dm-cli account status [параметры] <биткоин адрес>

    Показать информацию о пользователе bitdeals.

    -f|--feedbacks [p|n]      Показать последнюю 1 тыс. полученных отзывов.
                              Используй p или n для фильтрации только позитивных или негативных отзывов.
    -i|--info                 Показать данные учётной записи.
    -r|--rating               Показать данные рейтинга.
    -s|--status               Показать статус пользователя (действие по умолчанию).   
)"
				  << std::endl;
	}
	else
	{
		std::cout <<
			R"(
Usage: dm-cli account status [options] <bitcoin_address>

    Show info about a bitdeals user.

    -f|--feedbacks [p|n]      Show last 1K received feedbacks.
                              Use p or n to filter only positive or negative feedbacks.
    -i|--info                 Show user account details.
    -r|--rating               Show user rating information.
    -s|--status               Show user account status (default action).   
)"
				  << std::endl;
	}
}

/// @brief Получение информации аккаунта
/// @param address  адресс АПИ
/// @param bkaddress  номер кошелька
/// @param isDebug флаг отладки
int AccountStatus(const std::string address, const char *bkaddress, bool isDebug)
{
	// curl "https://testnet-dm.bitdeals.org/api/v1/account/status?address=mnumHs9HQMrw2Q1iKLNnx9NzExS7nMLmyp"
	string url("curl -s ");
	url += address + "/api/v1/account/status?address=" + bkaddress;
	string result = ExecCommand(url.c_str());
	if (result.length() == 0)
		return NoResponse("");
	nlohmann::json jsonData = nlohmann::json::parse(result);

	string payload("");
	payload = jsonData["payload"];
	bool success = jsonData["result"]["success"];

	string decoded = base64_decode(payload);
	string cleaned = cleanup_html(decoded);
	cout << cleaned << endl;
	if (isDebug)
		ShowDebug(url, result, success, decoded);
	if (success)
		return 0;
	else
		return 1;
}

/// @brief Получение информации аккаунта
/// @param address  адресс АПИ
/// @param bkaddress  номер кошелька
/// @param isDebug флаг отладки
int AccountInfo(const std::string address, const char *bkaddress, bool isDebug)
{

	// curl -H "Content-Type: application/json" -d "{ \"code\": \"mnumHs9HQMrw2Q1iKLNnx9NzExS7nMLmyp\"}" https://testnet-dm2.bitdeals.org/api/v1/user/profile
	string url("curl -s ");
	url.append("-H \"Content-Type: application/json\" ");
	url.append("-d \"{ \\\"code\\\": \\\"");
	url.append(bkaddress);
	url.append("\\\"} \" ");
	url.append(address);
	url.append("/api/v1/user/profile");

	string result = ExecCommand(url.c_str());
	if (result.length() == 0)
		return NoResponse("");
	nlohmann::json jsonData = nlohmann::json::parse(result);

	string bitcoin("");
	string btckey("");
	string bitmessage("");
	string pgpkey("");

	bitcoin = bkaddress;
	btckey = jsonData["btckey"];
	bitmessage = jsonData["bitmessages"][0];
	pgpkey = jsonData["pgpkey"];

	string decoded("");
	decoded.append("bitcoin: ");
	decoded.append(bitcoin);
	decoded.append("\n");

	decoded.append("btckey: ");
	decoded.append(btckey);
	decoded.append("\n");

	decoded.append("bitmessage: ");
	decoded.append(bitmessage);
	decoded.append("\n");

	decoded.append("pgpkey: ");
	decoded.append(pgpkey);
	decoded.append("\n");

	cout << decoded << endl;

	if (isDebug)
		ShowDebug(url, result, 1, decoded);

	return 0;
}

/// @brief Получение Рейтинга аккаунта
/// @param address  адресс АПИ
/// @param bkaddress  номер кошелька
/// @param isDebug флаг отладки
int AccountRaiting(const std::string address, const char *bkaddress, bool isDebug)
{
	// curl -H "Content-Type: application/json" -d "{ \"code\": \"mnumHs9HQMrw2Q1iKLNnx9NzExS7nMLmyp\"}" https://testnet-dm2.bitdeals.org/api/v1/user/profile
	string url("curl -s ");
	url.append("-H \"Content-Type: application/json\" ");
	url.append("-d \"{ \\\"code\\\": \\\"");
	url.append(bkaddress);
	url.append("\\\"} \" ");
	url.append(address);
	url.append("/api/v1/user/profile");

	string result = ExecCommand(url.c_str());
	if (result.length() == 0)
		return NoResponse("");
	nlohmann::json jsonData = nlohmann::json::parse(result);

	std::ostringstream stream;

	stream << "created: " << jsonData["created"] << endl;
	stream << "seller: " << endl;
	stream << "    count: " << jsonData["seller"]["count"] << endl;
	stream << "    positive: " << jsonData["seller"]["positive"] << endl;

	stream << "customer: " << endl;
	stream << "    count: " << jsonData["customer"]["count"] << endl;
	stream << "    positive: " << jsonData["customer"]["positive"] << endl;

	string decoded = stream.str();
	cout << decoded << endl;

	if (isDebug)
		ShowDebug(url, result, 1, decoded);

	return 0;
}

/// @brief Получение Рейтинга аккаунта
/// @param address  адресс АПИ
/// @param bkaddress  номер кошелька
/// @param isDebug флаг отладки
/// @param fb - тип фидбэка 0- все p - 1(positive) n-2 (negative)
int AccountFeedbacks(const std::string address, const char *bkaddress, bool isDebug, int fb)
{

	/*
	curl -X POST "https://testnet-dm2.bitdeals.org/api/v1/deal/feedback/list" \
	-H "Content-Type: application/json" \
	-d '{"search":[{"field":"sellercode","compare":"EQL","value":"mraXx7JrmAmuKypdJ1vseQBXySsdRZE5AC"}],"orderby":["date DESC"],"reclimit":1000,"recoffset":0}'


	*/
	string url("curl -s ");
	url.append("-H \"Content-Type: application/json\" ");

	url.append("-d \"{ \\\"search\\\":[{\\\"field\\\":\\\"sellercode\\\",\\\"compare\\\": \\\"EQL\\\",\\\"value\\\":\\\"");
	url.append(bkaddress);
	url.append("\\\"}],\\\"orderby\\\":[\\\" date DESC\\\"],\\\"reclimit\\\":100,\\\"recoffset\\\":0} \" ");

	url.append(address);
	url.append("/api/v1/deal/feedback/list");

	string result = ExecCommand(url.c_str());
	if (result.length() == 0)
		return NoResponse("");
	nlohmann::json jsonData = nlohmann::json::parse(result);

	std::ostringstream stream;
	size_t size = jsonData.size();
	int positivefb = 0;
	int negativefb = 0;

	for (size_t i = 0; i < size; ++i)
	{
		// "positive"
		// "negative"
		// 0 - все p - 1(positive)n - 2 (negative)

		auto val = jsonData[i];
		string statustext = val["statustext"];

		if (statustext.compare("positive") == 0)
			positivefb++;
		if (statustext.compare("negative") == 0)
			negativefb++;
		if (statustext.compare("neutral") == 0)
			negativefb++;

		if (fb == 0)
		{
			stream << "- deal: " << val["deal"] << endl;
			stream << "  date: " << val["date"] << endl;
			stream << "  statustext: " << val["statustext"] << endl;
			stream << "  comments: " << val["comments"] << endl;
		}

		if (fb == 1 && statustext.compare("positive") == 0)
		{
			stream << "- deal: " << val["deal"] << endl;
			stream << "  date: " << val["date"] << endl;
			stream << "  statustext: " << val["statustext"] << endl;
			stream << "  comments: " << val["comments"] << endl;
		}
		if ((fb == 2 && statustext.compare("negative") == 0) || (fb == 2 && statustext.compare("neutral") == 0))
		{
			stream << "- deal: " << val["deal"] << endl;
			stream << "  date: " << val["date"] << endl;
			stream << "  statustext: " << val["statustext"] << endl;
			stream << "  comments: " << val["comments"] << endl;
		}
	}
	stream << "------------Summary--------------" << endl;
	stream << "total: " << size << endl;
	stream << "positive: " << positivefb << endl;
	stream << "neegative: " << negativefb << endl;

	string decoded = stream.str();
	cout << decoded << endl;

	if (isDebug)
		ShowDebug(url, result, 1, decoded);

	return 0;

	return 0;
}