#include "track/media.h"
#include "track/constants.h"
#include "animia.h"
#include "anitomy/anitomy.h"
#include "core/filesystem.h"
#include "core/strings.h"
#include "core/session.h"
#include <string>
#include <unordered_map>
#include <vector>
#include <iostream>

namespace Track {
namespace Media {

std::vector<Filesystem::Path> GetCurrentlyPlayingFiles() {
	/* getting all open files */
	std::vector<Filesystem::Path> ret;

	std::vector<int> pids = Animia::get_all_pids();
	for (int pid : pids) {
		for (const Types::MediaPlayer& player : session.recognition.players) {
			if (!player.GetEnabled() || Animia::get_process_name(pid) != player.GetExecutable())
				continue;

			for (const std::string& file : Animia::filter_system_files(Animia::get_open_files(pid))) {
				const Filesystem::Path path(file);

				for (const Types::MediaExtension& ext : session.recognition.extensions)
					if (path.Extension() == ext.GetExtension())
						ret.push_back(path);
			}
		}
	}

	return ret;
}

Filesystem::Path GetCurrentPlaying() {
	/* getting all open files */
	std::vector<Filesystem::Path> paths = GetCurrentlyPlayingFiles();
	if (paths.size())
		return paths.at(0);
	return Filesystem::Path();
}

std::unordered_map<std::string, std::string> GetMapFromElements(const anitomy::Elements& elements) {
	/* there are way more than this in anitomy, but we only need basic information
	   I also just prefer using maps than using the ".get()" stuff which is why I'm doing this */
	std::unordered_map<std::string, std::string> ret;

	ret["title"] = Strings::ToUtf8String(elements.get(anitomy::kElementAnimeTitle));
	ret["filename"] = Strings::ToUtf8String(elements.get(anitomy::kElementFileName));
	ret["language"] = Strings::ToUtf8String(elements.get(anitomy::kElementLanguage));
	ret["group"] = Strings::ToUtf8String(elements.get(anitomy::kElementReleaseGroup));
	ret["episode"] = Strings::ToUtf8String(elements.get(anitomy::kElementEpisodeNumber));
	ret["resolution"] = Strings::ToUtf8String(elements.get(anitomy::kElementVideoResolution));

	return ret;
}

std::unordered_map<std::string, std::string> GetFileElements(std::string basename) {
	anitomy::Anitomy anitomy;
	anitomy.Parse(Strings::ToWstring(basename));

	return GetMapFromElements(anitomy.elements());
}

std::unordered_map<std::string, std::string> GetFileElements(Filesystem::Path path) {
	anitomy::Anitomy anitomy;
	anitomy.Parse(Strings::ToWstring(path.Basename()));

	return GetMapFromElements(anitomy.elements());
}

} // namespace Media
} // namespace Track
