#include "window.h"
#include "ui_utils.h"
#include <sstream>

StatisticsTimer::StatisticsTimer(Statistics* caller) {
	statistics = caller;
}

void StatisticsTimer::Notify() {
	if (status.current_page == PAGE_STATISTICS)
		statistics->UpdateStatistics();
}

Statistics::Statistics(page_t* page, wxPanel* frame) {
	page->panel = new wxPanel(frame, wxID_ANY, wxPoint(0, 0), wxSize(400, 600));
	page->panel->Show(false);
	panel = new wxPanel(page->panel, wxID_ANY, wxPoint(12, 12), wxSize(376, 576));
	anime_list = ((WeeabooFrame*)frame->GetParent())->GetAnimeList();

	/* FIXME: this should be moved to a separate function, it's also used in information.cpp */
	// wxWindow* parent, const char* title, const char* label, const char* data, int width, int height, int x = 0, int y = 0, int selectable = 0
	anime_list_data = UiUtils::CreateTextParagraphWithLabels(panel, L"Anime list", L"Anime count:\nEpisode count:\nTime spent watching:\nTime to complete:\nAverage score:\nScore deviation:", L"", 376, 94);

	UpdateStatistics(); // load in statistics as soon as possible
	timer = new StatisticsTimer(this);
	timer->Start(1000); // update statistics every second
}

std::string Statistics::MinutesToDateString(int minutes) {
	/* NOTE: these duration_casts may not be needed... */
	std::chrono::duration<int, std::ratio<60>> int_total_mins(minutes);
	auto int_years = std::chrono::duration_cast<std::chrono::years>(int_total_mins);
	auto int_months = std::chrono::duration_cast<std::chrono::months>(int_total_mins-int_years);
	auto int_days = std::chrono::duration_cast<std::chrono::days>(int_total_mins-int_years-int_months);
	auto int_hours = std::chrono::duration_cast<std::chrono::hours>(int_total_mins-int_years-int_months-int_days);
	auto int_minutes = std::chrono::duration_cast<std::chrono::minutes>(int_total_mins-int_years-int_months-int_days-int_hours);
	std::ostringstream return_stream;
	if (int_years.count() > 0) {
		return_stream << int_years.count() << " years ";
	}
	if (int_months.count() > 0) {
		return_stream << int_months.count() << " months ";
	}
	if (int_days.count() > 0) {
		return_stream << int_days.count() << " days ";
	}
	if (int_hours.count() > 0) {
		return_stream << int_hours.count() << " hours ";
	}
	return_stream << int_minutes.count() << " minutes"; // return minutes anyway
	return return_stream.str();
}

void Statistics::UpdateStatistics() {
	wxString string = "";
	string << anime_list->GetTotalAnimeAmount() << '\n';
	string << anime_list->GetTotalEpisodeAmount() << '\n';
	string << MinutesToDateString(anime_list->GetTotalWatchedAmount()) << '\n';
	string << MinutesToDateString(anime_list->GetTotalPlannedAmount()) << '\n';
	string << anime_list->GetAverageScore() << '\n';
	string << anime_list->GetScoreDeviation() << '\n';
	anime_list_data->SetLabel(string);
}
