#include "cache.h"
#include "common.h"

#include <cmath>
#include <ctime>

Position Cache::home;

static float degtorad(float x) {
	return x * M_PI / 180;
}

void Cache::show() const {
	std::cout << "Cache:\t" << code << ' ' << name << " (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::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, "%F", &date_tm);
	date = tmp;
}

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;
}

float cache_distance(const Cache& a, const Cache& b) {
	return 2 * Earth_radius * asin(sqrt(pow(sin(degtorad((a.pos.lat - b.pos.lat) / 2)), 2) + cos(degtorad(a.pos.lat)) * cos(degtorad(b.pos.lat)) * pow(sin(degtorad((a.pos.lon - b.pos.lon) / 2)), 2)));
}
