#include "cache.h"

#include <cmath>

void Cache::show() const {
	std::cout << "Cache:\t" << code << ' ' << name << " (";
	if (status == ok)
		std::cout << "OK";
	else if (status == disabled)
		std::cout << "DIS";
	else if (status == archived)
		std::cout << "ARCH";
	else
		std::cout << "UNK";
	std::cout << " type: " << type << ", owned by " << owner << ")\n";
	std::cout << '\t' << pos.lat << " " << pos.lon << "\t\tD/T: " << diff << '/' << terr << "\t\tSize: " << size << "\t\tFound on " << date << '\n';
	std::cout << "Region: " << region << "\t\tSubregion: " << subregion << '\n';
}

std::string Cache::link() const {
	return "http://coord.eu/" + code;
}

std::string Cache::link_name() const {
	if (recommended)
		return "<a class=\"fav\" href=\"" + link() + "\">" + safe_name() + " (" + code + ")</a>";
	else
		return "<a href=\"" + link() + "\">" + safe_name() + " (" + code + ")</a>";
}

std::string Cache::safe_name() const {
	std::string tmp = name;
	htmlencode(tmp);
	return tmp;
}

// float Cache::distance() const {
// 	return 2 * Earth_radius * asin(sqrt(pow(sin(degtorad((pos.lat - home.lat) / 2)), 2) + cos(degtorad(pos.lat)) * cos(degtorad(home.lat)) * pow(sin(degtorad((pos.lon - home.lon) / 2)), 2)));
// }

void Cache::set_date(const std::tm& t) {
	char tmp[20];

	date_tm = t;
	date_t = std::mktime(&date_tm);

	year = std::to_string(1900 + date_tm.tm_year);
	std::strftime(tmp, 20, "(%m) %B", &date_tm);
	mon = tmp;
	day = std::to_string(date_tm.tm_mday);
	hour = std::to_string(date_tm.tm_hour);
	std::strftime(tmp, 20, "(%u) %A", &date_tm);
	day_of_week = tmp;
	std::strftime(tmp, 20, "%Y %m", &date_tm);
	year_month = tmp;

	std::strftime(tmp, 20, "%F", &date_tm);
	date = tmp;

	// this function should be run after set_date_hidden()
	if (date_hidden_t == 0) throw 1;
	age_when_found = (date_t - date_hidden_t) / (60 * 60 * 24);
}

void Cache::set_date_hidden(const std::tm& t) {
	char tmp[20];

	date_hidden_tm = t;
	date_hidden_t = std::mktime(&date_hidden_tm);

	std::strftime(tmp, 20, "%F", &date_hidden_tm);
	date_hidden = tmp;

	age_now = (std::time(nullptr) - date_hidden_t) / (60 * 60 * 24);
}
