/*
 * What the weather looks like in words and numbers: the NWS's icon codes
 * as the glyphs Start draws, temperatures, wind and pressure in the units
 * chosen, METAR present weather in words, and the sky behind it all.
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "clock.h"
#include "weather.h"

/* The NWS's icon names (api.weather.gov's) after "day:" or "night:" */
static const struct {
	const char *code, *glyph;
} glyphs[] = {
	{ "skc", "clear" }, { "wind_skc", "clear" }, { "hot", "clear" },
	{ "cold", "clear" },
	{ "few", "partly" }, { "sct", "partly" }, { "wind_few", "partly" },
	{ "wind_sct", "partly" },
	{ "bkn", "cloudy" }, { "ovc", "cloudy" }, { "wind_bkn", "cloudy" },
	{ "wind_ovc", "cloudy" },
	{ "fog", "fog" }, { "haze", "fog" }, { "smoke", "fog" }, { "dust", "fog" },
	{ "rain", "rain" }, { "rain_showers", "rain" },
	{ "rain_showers_hi", "rain" },
	{ "snow", "snow" }, { "blizzard", "snow" },
	{ "sleet", "sleet" }, { "fzra", "sleet" }, { "rain_snow", "sleet" },
	{ "rain_sleet", "sleet" }, { "snow_sleet", "sleet" },
	{ "rain_fzra", "sleet" }, { "snow_fzra", "sleet" },
	{ "tsra", "thunder" }, { "tsra_sct", "thunder" }, { "tsra_hi", "thunder" },
	{ "tornado", "thunder" }, { "hurricane", "thunder" },
	{ "tropical_storm", "thunder" },
};

bool ws_icon_is_night(const char *icon) {
	return icon && g_str_has_prefix(icon, "night:");
}

const char *ws_glyph(const char *icon) {
	if (icon == NULL) {
		return "cloudy";
	}
	const char *colon = strchr(icon, ':');
	const char *code = colon ? colon + 1 : icon;
	bool night = ws_icon_is_night(icon);
	for (size_t i = 0; i < G_N_ELEMENTS(glyphs); i++) {
		/* "rain_showers,20": a chance after the comma */
		size_t n = strlen(glyphs[i].code);
		if (strncmp(code, glyphs[i].code, n) == 0 &&
				(code[n] == '\0' || code[n] == ',')) {
			const char *g = glyphs[i].glyph;
			if (night && strcmp(g, "clear") == 0) {
				return "night";
			}
			if (night && strcmp(g, "partly") == 0) {
				return "partly-night";
			}
			return g;
		}
	}
	return "cloudy";
}

static bool is_descriptor(const char *p) {
	static const char *const d[] = { "FZ", "BL", "DR", "MI", "BC", "PR" };
	for (size_t i = 0; i < G_N_ELEMENTS(d); i++) {
		if (strncmp(p, d[i], 2) == 0) {
			return true;
		}
	}
	return false;
}

/* METAR's present weather: "-SHRA" is light rain showers */
static char *ws_metar_words(const char *weather) {
	if (weather == NULL || weather[0] == '\0') {
		return NULL;
	}
	static const struct {
		const char *code, *word;
	} parts[] = {
		{ "TS", "thunderstorm" }, { "SH", "showers" }, { "FZ", "freezing" },
		{ "BL", "blowing" }, { "DR", "drifting" }, { "MI", "shallow" },
		{ "BC", "patches of" }, { "PR", "partial" },
		{ "DZ", "drizzle" }, { "RA", "rain" }, { "SN", "snow" },
		{ "SG", "snow grains" }, { "IC", "ice crystals" }, { "PL", "sleet" },
		{ "GR", "hail" }, { "GS", "small hail" }, { "UP", "precipitation" },
		{ "BR", "mist" }, { "FG", "fog" }, { "FU", "smoke" }, { "VA", "ash" },
		{ "DU", "dust" }, { "SA", "sand" }, { "HZ", "haze" }, { "PY", "spray" },
		{ "PO", "dust whirls" }, { "SQ", "squalls" }, { "FC", "funnel cloud" },
		{ "SS", "sandstorm" }, { "DS", "dust storm" },
	};
	/* Only the first group: "-RA BR" is light rain (and mist) */
	char *first = g_strndup(weather, strcspn(weather, " "));
	const char *p = first;
	GString *out = g_string_new(NULL);
	if (*p == '-') {
		g_string_append(out, "light ");
		p++;
	} else if (*p == '+') {
		g_string_append(out, "heavy ");
		p++;
	}
	if (strncmp(p, "VC", 2) == 0) {
		p += 2; // in the vicinity: said the same
	}
	GPtrArray *words = g_ptr_array_new();
	GString *adjectives = g_string_new(NULL);
	const char *showers = NULL;
	while (p[0] && p[1]) {
		const char *word = NULL;
		for (size_t i = 0; i < G_N_ELEMENTS(parts); i++) {
			if (strncmp(p, parts[i].code, 2) == 0) {
				word = parts[i].word;
				break;
			}
		}
		if (word == NULL) {
			break;
		}
		/* Showers go after what falls: "rain showers"; the other
		 * descriptors before it: "freezing fog" */
		if (strcmp(word, "showers") == 0) {
			showers = word;
		} else if (p - first < 4 && is_descriptor(p)) {
			g_string_append_printf(adjectives, "%s ", word);
		} else {
			g_ptr_array_add(words, (gpointer)word);
		}
		p += 2;
	}
	g_string_append(out, adjectives->str);
	g_string_free(adjectives, TRUE);
	for (guint i = 0; i < words->len; i++) {
		const char *w = words->pdata[i];
		if (i > 0) {
			/* "thunderstorm" then what it brings */
			g_string_append(out, i == 1 && strcmp(words->pdata[0],
				"thunderstorm") == 0 ? " with " : " and ");
		}
		g_string_append(out, w);
	}
	if (showers) {
		g_string_append_printf(out, "%s%s", words->len ? " " : "", showers);
	}
	g_ptr_array_unref(words);
	g_free(first);
	if (out->len == 0 || g_str_has_suffix(out->str, " ")) {
		g_string_free(out, TRUE);
		return NULL;
	}
	out->str[0] = g_ascii_toupper(out->str[0]);
	return g_string_free(out, FALSE);
}

/* The hour now, from the forecast: what the sky is like */
static struct ws_hour *hour_now(struct ws_place *p) {
	if (p->forecast == NULL || p->forecast->hours->len == 0) {
		return NULL;
	}
	return &g_array_index(p->forecast->hours, struct ws_hour, 0);
}

const char *ws_now_summary(struct ws_place *p) {
	/* What is falling, as the station sees it, wins: the forecast says
	 * what was expected */
	static char *said;
	g_clear_pointer(&said, g_free);
	if (p->now && p->now->weather) {
		said = ws_metar_words(p->now->weather);
		if (said) {
			return said;
		}
	}
	struct ws_hour *h = hour_now(p);
	if (h && h->summary) {
		return h->summary;
	}
	if (p->forecast && p->forecast->days->len) {
		return g_array_index(p->forecast->days, struct ws_day, 0).summary;
	}
	return NULL;
}

/* What the station sees falling, as an icon code; NULL for nothing */
static const char *metar_code(const char *weather) {
	if (weather == NULL) {
		return NULL;
	}
	if (strstr(weather, "TS")) {
		return "tsra";
	}
	if (strstr(weather, "FZ") && (strstr(weather, "RA") ||
			strstr(weather, "DZ"))) {
		return "fzra";
	}
	if (strstr(weather, "PL") || strstr(weather, "GR") ||
			strstr(weather, "GS")) {
		return "sleet";
	}
	if (strstr(weather, "SN") || strstr(weather, "SG")) {
		return strstr(weather, "RA") ? "rain_snow" : "snow";
	}
	if (strstr(weather, "RA") || strstr(weather, "DZ") ||
			strstr(weather, "UP")) {
		return "rain";
	}
	if (strstr(weather, "FG") || strstr(weather, "BR") ||
			strstr(weather, "HZ") || strstr(weather, "FU") ||
			strstr(weather, "DU") || strstr(weather, "SA")) {
		return "fog";
	}
	return NULL;
}

const char *ws_now_icon(struct ws_place *p) {
	struct ws_hour *h = hour_now(p);
	const char *forecast = h && h->icon ? h->icon : p->forecast &&
		p->forecast->days->len ? g_array_index(p->forecast->days,
		struct ws_day, 0).icon : NULL;
	/* As the summary does: what's falling now beats what was expected */
	const char *seen = p->now ? metar_code(p->now->weather) : NULL;
	if (seen) {
		static char icon[32];
		bool night;
		if (forecast) {
			night = ws_icon_is_night(forecast);
		} else {
			GDateTime *now = g_date_time_new_now_local();
			int hour = g_date_time_get_hour(now);
			g_date_time_unref(now);
			night = hour < 6 || hour >= 19;
		}
		snprintf(icon, sizeof(icon), "%s:%s", night ? "night" : "day", seen);
		return icon;
	}
	return forecast;
}

/* Numbers */

/* In the units chosen */
static double ws_temp_value(double c) {
	return ws_settings.units == WS_CELSIUS ? c : c * 9 / 5 + 32;
}

char *ws_temp(double c, bool units) {
	if (isnan(c)) {
		return g_strdup("--");
	}
	long v = lround(ws_temp_value(c));
	if (v == 0) {
		v = 0; // no "-0"
	}
	return g_strdup_printf("%ld°%s", v, !units ? "" :
		ws_settings.units == WS_CELSIUS ? "C" : "F");
}

static const char *compass(double deg) {
	static const char *const points[] = { "N", "NNE", "NE", "ENE", "E", "ESE",
		"SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW" };
	int i = (int)lround(fmod(fmod(deg, 360) + 360, 360) / 22.5) % 16;
	return points[i];
}

static char *speed(double kmh) {
	if (ws_settings.units == WS_CELSIUS) {
		return g_strdup_printf("%ld km/h", lround(kmh));
	}
	return g_strdup_printf("%ld mph", lround(kmh / 1.609344));
}

char *ws_wind(double kt, double dir) {
	if (isnan(kt)) {
		return g_strdup("--");
	}
	if (kt < 1) {
		return g_strdup("Calm");
	}
	char *s = speed(kt * 1.852);
	char *out = isnan(dir) ? g_strdup_printf("Variable %s", s) :
		g_strdup_printf("%s %s", compass(dir), s);
	g_free(s);
	return out;
}

char *ws_wind_kmh(double kmh, const char *dir) {
	if (isnan(kmh)) {
		return g_strdup("--");
	}
	char *s = speed(kmh);
	char *out = dir && dir[0] ? g_strdup_printf("%s %s", dir, s) : g_strdup(s);
	g_free(s);
	return out;
}

char *ws_pressure(double hpa) {
	if (isnan(hpa)) {
		return g_strdup("--");
	}
	if (ws_settings.units == WS_CELSIUS) {
		return g_strdup_printf("%.0f hPa", hpa);
	}
	return g_strdup_printf("%.2f in", hpa * 0.0295300);
}

/* The NWS's wind chill and heat index, in °F as they're defined */
double ws_feels_like(struct ws_now *n) {
	if (n == NULL || isnan(n->temp)) {
		return NAN;
	}
	double t = n->temp * 9 / 5 + 32;
	double mph = isnan(n->wind_kt) ? 0 : n->wind_kt * 1.150779;
	double f = t;
	if (t <= 50 && mph > 3) {
		double v = pow(mph, 0.16);
		f = 35.74 + 0.6215 * t - 35.75 * v + 0.4275 * t * v;
	} else if (t >= 80 && !isnan(n->humidity)) {
		double rh = n->humidity;
		double simple = 0.5 * (t + 61 + (t - 68) * 1.2 + rh * 0.094);
		f = simple;
		if ((simple + t) / 2 >= 80) {
			f = -42.379 + 2.04901523 * t + 10.14333127 * rh -
				0.22475541 * t * rh - 0.00683783 * t * t -
				0.05481717 * rh * rh + 0.00122874 * t * t * rh +
				0.00085282 * t * rh * rh - 0.00000199 * t * t * rh * rh;
		}
	}
	return (f - 32) * 5 / 9;
}

/* Words for times */

bool ws_clock_24h(void) {
	static char *mode;
	static int64_t read_at;
	int64_t now = g_get_monotonic_time() / G_USEC_PER_SEC;
	/* Read now and then: PC settings may change it */
	if (mode == NULL || now - read_at > 60) {
		read_at = now;
		g_clear_pointer(&mode, g_free);
		GKeyFile *kf = g_key_file_new();
		char *path = g_build_filename(g_get_user_config_dir(), "cont8nuum",
			"config.ini", NULL);
		if (g_key_file_load_from_file(kf, path, G_KEY_FILE_NONE, NULL)) {
			mode = g_key_file_get_string(kf, "general", "clock", NULL);
		}
		if (mode == NULL) {
			mode = g_strdup("auto");
		}
		g_free(path);
		g_key_file_free(kf);
	}
	return !clock_12h(mode);
}

char *ws_day_label(struct ws_day *d, int index) {
	if (index == 0) {
		return g_strdup("Today");
	}
	GDate date;
	g_date_clear(&date, 1);
	g_date_set_parse(&date, d->date);
	if (!g_date_valid(&date)) {
		int y, m, dd;
		if (sscanf(d->date, "%d-%d-%d", &y, &m, &dd) == 3 &&
				g_date_valid_dmy(dd, m, y)) {
			g_date_set_dmy(&date, dd, m, y);
		}
	}
	if (!g_date_valid(&date)) {
		return g_strdup(d->name ? d->name : "");
	}
	char buf[32];
	g_date_strftime(buf, sizeof(buf), "%a %e", &date);
	char *out = g_strdup(buf);
	/* "%e" pads with a space */
	char *dbl = strstr(out, "  ");
	if (dbl) {
		memmove(dbl, dbl + 1, strlen(dbl));
	}
	return out;
}

char *ws_hour_label(GDateTime *t) {
	if (ws_clock_24h()) {
		return g_date_time_format(t, "%H:00");
	}
	int h = g_date_time_get_hour(t);
	return g_strdup_printf("%d %s", h % 12 ? h % 12 : 12, h < 12 ? "AM" : "PM");
}

char *ws_age(int64_t when) {
	if (when <= 0) {
		return g_strdup("");
	}
	time_t t = (time_t)when;
	struct tm tm;
	localtime_r(&t, &tm);
	char buf[32];
	clock_format(buf, sizeof(buf), &tm, ws_clock_24h() ? "24" : "12", true);
	int64_t now = g_get_real_time() / G_USEC_PER_SEC;
	if (now - when > 20 * 3600) {
		char day[32];
		strftime(day, sizeof(day), "%a", &tm);
		return g_strdup_printf("Updated %s %s", day, buf);
	}
	return g_strdup_printf("Updated %s", buf);
}

/* The sky: a gradient for each kind of weather, by day and by night, in
 * place of the photographs Windows 8's Weather had */
static const struct {
	const char *glyph;
	uint32_t top, bottom;
} skies[] = {
	{ "clear", 0x1f6fc4, 0x79b6e8 },
	{ "partly", 0x2f6fae, 0x8fb4d6 },
	{ "cloudy", 0x56657a, 0x9aa7b5 },
	{ "fog", 0x6c7782, 0xa7afb6 },
	{ "rain", 0x2f3c4c, 0x66788a },
	{ "sleet", 0x3b4a5e, 0x7b8ba0 },
	{ "snow", 0x56708f, 0x9db2c9 },
	{ "thunder", 0x1f2232, 0x544d6b },
	{ "night", 0x08112a, 0x203761 },
	{ "partly-night", 0x0f1a30, 0x34465f },
};

uint32_t ws_sky_top(const char *glyph) {
	for (size_t i = 0; glyph && i < G_N_ELEMENTS(skies); i++) {
		if (strcmp(skies[i].glyph, glyph) == 0) {
			return skies[i].top;
		}
	}
	return 0x2f6fae;
}

uint32_t ws_sky_bottom(const char *glyph) {
	for (size_t i = 0; glyph && i < G_N_ELEMENTS(skies); i++) {
		if (strcmp(skies[i].glyph, glyph) == 0) {
			return skies[i].bottom;
		}
	}
	return 0x8fb4d6;
}
