/*
This file is part of Telegram Desktop,
the official desktop application for the Telegram messaging service.

For license and copyright information please follow this link:
https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
*/
#pragma once

#include "base/flat_set.h"

class QDebug;

namespace MTP {

class Error {
public:
	explicit Error(const MTPrpcError &error);
	explicit Error(const mtpBuffer &reply);

	enum {
		NoError,
		TimeoutError
	};

	[[nodiscard]] int32 code() const;
	[[nodiscard]] const QString &type() const;
	[[nodiscard]] const QString &description() const;

	[[nodiscard]] static Error Local(
		const QString &type,
		const QString &description);
	[[nodiscard]] static MTPrpcError MTPLocal(
		const QString &type,
		const QString &description);

private:
	int32 _code = 0;
	QString _type, _description;

};

inline bool IsFloodError(const QString &type) {
	return type.startsWith(u"FLOOD_WAIT_"_q)
		|| type.startsWith(u"FLOOD_PREMIUM_WAIT_"_q);
}

inline bool IsFloodError(const Error &error) {
	return IsFloodError(error.type());
}

inline bool IsTemporaryError(const Error &error) {
	return error.code() < 0 || error.code() >= 500 || IsFloodError(error);
}

inline bool IsDefaultHandledError(const Error &error) {
	return IsTemporaryError(error);
}

inline bool IgnoreError(const Error &error) {
	return error.code() == 406;
}

template <typename ShowPtr>
void ShowErrorFallback(const ShowPtr &show, const Error &error) {
	if (!IgnoreError(error)) {
		show->showToast(error.type());
	}
}

struct Response {
	mtpBuffer reply;
	mtpMsgId outerMsgId = 0;
	mtpRequestId requestId = 0;
};

using DoneHandler = FnMut<bool(const Response&)>;
using FailHandler = Fn<bool(const Error&, const Response&)>;

struct ResponseHandler {
	DoneHandler done;
	FailHandler fail;
};

[[nodiscard]] QDebug operator<<(QDebug debug, const Error &error);

} // namespace MTP
