#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <langinfo.h>
#include <time.h>
#include "clock.h"
#include "json.h"
#include "stealth.h"
#include "widget.h"

/* Clock: the time, large, and the date */

struct clock {
	char shown[8]; // the minute sent last
};

static void clock_tick(struct widget *w) {
	struct clock *c = w->data;
	char minute[8];
	time_t now = time(NULL);
	strftime(minute, sizeof(minute), "%H:%M", localtime(&now));
	if (strcmp(minute, c->shown) != 0) {
		snprintf(c->shown, sizeof(c->shown), "%s", minute);
		widget_update(w);
	}
}

static void clock_content(struct widget *w, struct content *c) {
	time_t now = time(NULL);
	struct tm tm;
	localtime_r(&now, &tm);
	char buf[64];
	set(c, "template", "block");
	clock_format(buf, sizeof(buf), &tm, clock_mode(), false);
	set(c, "block", "%s", buf);
	strftime(buf, sizeof(buf), "%A", &tm);
	set(c, "text1", "%s", buf);
	strftime(buf, sizeof(buf), "%-d %B", &tm);
	set(c, "text2", "%s", buf);
}

static bool clock_init(struct widget *w, int argc, char **argv) {
	w->data = g_new0(struct clock, 1);
	return true;
}

const struct widget_kind kind_clock = {
	.name = "clock",
	.summary = "The time and date",
	.tick_ms = 1000,
	.init = clock_init,
	.tick = clock_tick,
	.content = clock_content,
};

/* Calendar: today, large, and the month */

struct calendar {
	char shown[16]; // the date sent last
};

static void calendar_tick(struct widget *w) {
	struct calendar *c = w->data;
	char today[16];
	time_t now = time(NULL);
	strftime(today, sizeof(today), "%Y-%m-%d", localtime(&now));
	if (strcmp(today, c->shown) != 0) {
		snprintf(c->shown, sizeof(c->shown), "%s", today);
		widget_update(w);
	}
}

/* 0 for Sunday, 1 for Monday...: the locale's first day of the week */
static int first_weekday(void) {
	/* glibc: the date of a known first day (a Sunday is 19971130) and
	 * the offset from it */
	int base = (int)(intptr_t)nl_langinfo(_NL_TIME_WEEK_1STDAY);
	int first = nl_langinfo(_NL_TIME_FIRST_WEEKDAY)[0];
	int sunday = 19971130;
	int days = 0;
	if (base != sunday) {
		days = base - sunday; // only 19971201 onwards are in use
	}
	return ((days + first - 1) % 7 + 7) % 7;
}

static void calendar_content(struct widget *w, struct content *c) {
	time_t now = time(NULL);
	struct tm tm;
	localtime_r(&now, &tm);
	char buf[64];
	set(c, "template", "calendar");
	set(c, "block", "%d", tm.tm_mday);
	set(c, "today", "%d", tm.tm_mday);
	set(c, "month", "%04d-%02d", tm.tm_year + 1900, tm.tm_mon + 1);
	set(c, "weekstart", "%d", first_weekday());
	strftime(buf, sizeof(buf), "%A", &tm);
	set(c, "text1", "%s", buf);
	strftime(buf, sizeof(buf), "%B %Y", &tm);
	set(c, "text2", "%s", buf);
	/* The extra lines (large tiles) */
	strftime(buf, sizeof(buf), "Week %V", &tm);
	set(c, "text3", "%s", buf);
	int year = tm.tm_year + 1900;
	bool leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
	int length = leap ? 366 : 365;
	set(c, "text4", "Day %d of %d", tm.tm_yday + 1, length);
	int left = length - tm.tm_yday - 1;
	set(c, "text5", "%d %s left", left, left == 1 ? "day" : "days");
	set(c, "label", "%s", "");
}

static bool calendar_init(struct widget *w, int argc, char **argv) {
	w->data = g_new0(struct calendar, 1);
	return true;
}

const struct widget_kind kind_calendar = {
	.name = "calendar",
	.summary = "Today's date and the month as a calendar",
	.tick_ms = 30000,
	.init = calendar_init,
	.tick = calendar_tick,
	.content = calendar_content,
};

/* World clocks: four mini tiles */

#define MAX_CLOCKS 4

struct clocks {
	int count;
	char *names[MAX_CLOCKS];
	GTimeZone *zones[MAX_CLOCKS];
	char shown[8];
};

static void clocks_tick(struct widget *w) {
	struct clocks *c = w->data;
	char minute[8];
	time_t now = time(NULL);
	strftime(minute, sizeof(minute), "%H:%M", gmtime(&now));
	if (strcmp(minute, c->shown) != 0) {
		snprintf(c->shown, sizeof(c->shown), "%s", minute);
		widget_update(w);
	}
}

static void clocks_content(struct widget *w, struct content *c) {
	struct clocks *cl = w->data;
	set(c, "template", "stats");
	for (int i = 0; i < cl->count; i++) {
		GDateTime *dt = g_date_time_new_now(cl->zones[i]);
		char *time = g_date_time_format(dt,
			clock_12h(clock_mode()) ? "%-I:%M %p" : "%H:%M");
		g_date_time_unref(dt);
		char key[16];
		snprintf(key, sizeof(key), "value%d", i + 1);
		set(c, key, "%s", time);
		snprintf(key, sizeof(key), "text%d", i + 1);
		set(c, key, "%s", cl->names[i]);
		g_free(time);
	}
}

static bool clocks_init(struct widget *w, int argc, char **argv) {
	struct clocks *c = g_new0(struct clocks, 1);
	const char *zones = "UTC=UTC,New York=America/New_York,"
		"London=Europe/London,Tokyo=Asia/Tokyo";
	for (int i = 1; i + 1 < argc; i += 2) {
		if (strcmp(argv[i], "--zones") == 0) {
			zones = argv[i + 1];
		} else {
			return false;
		}
	}
	char **list = g_strsplit(zones, ",", -1);
	for (char **z = list; *z && c->count < MAX_CLOCKS; z++) {
		char *eq = strchr(*z, '=');
		const char *id = eq ? eq + 1 : *z;
		GTimeZone *tz = g_time_zone_new_identifier(id);
		if (tz == NULL) {
			fprintf(stderr, "c8-widget: unknown time zone '%s'\n", id);
			continue;
		}
		c->names[c->count] = eq ? g_strndup(*z, eq - *z) : g_strdup(*z);
		c->zones[c->count++] = tz;
	}
	g_strfreev(list);
	w->data = c;
	return true;
}

const struct widget_kind kind_clocks = {
	.name = "clocks",
	.summary = "The time in up to four places",
	.options = "              --zones \"Name=Area/City,...\"   default UTC, New York,\n"
		"                                          London, Tokyo\n",
	.tick_ms = 1000,
	.init = clocks_init,
	.tick = clocks_tick,
	.content = clocks_content,
};

/* Weather, from wttr.in: now, today in three-hour slots, and three days */

#define WEATHER_MAX_AGE (30 * 60)

struct weather {
	char *url, *file;
	bool mph, fetching;
	struct json *data;
	time_t fetched;
};

static void weather_load(struct widget *w) {
	struct weather *wt = w->data;
	char *text = read_text(wt->file);
	struct json *data = json_parse(text);
	g_free(text);
	if (data && json_get(data, "current_condition")) {
		json_free(wt->data);
		wt->data = data;
		struct stat st;
		wt->fetched = stat(wt->file, &st) == 0 ? st.st_mtime : 0;
	} else {
		json_free(data);
	}
	widget_update(w);
}

static void weather_fetched(struct widget *w, const char *out) {
	struct weather *wt = w->data;
	wt->fetching = false;
	/* Only replace the cache with something that parses */
	struct json *data = json_parse(out);
	if (data && json_get(data, "current_condition")) {
		g_file_set_contents(wt->file, out, -1, NULL);
	}
	json_free(data);
	weather_load(w);
}

static void weather_tick(struct widget *w) {
	struct weather *wt = w->data;
	struct stat st;
	bool stale = stat(wt->file, &st) != 0 || time(NULL) - st.st_mtime > WEATHER_MAX_AGE;
	if (stale && !wt->fetching) {
		/* wttr.in serves JSON to curl */
		const char *const argv[] = { "curl", "-sf", "--max-time", "15", wt->url, NULL };
		wt->fetching = run_command(w, argv, weather_fetched);
	}
	/* Look again anyway: the cache may be newer */
	weather_load(w);
}

static const char *nested_value(struct json *obj, const char *key) {
	/* wttr.in wraps text as [{"value": "..."}] */
	return json_str(json_get(json_at(json_get(obj, key), 0), "value"), "");
}

/* wttr.in's weather codes, as the glyph Start draws */
static const char *weather_glyph(int code, bool night) {
	switch (code) {
	case 113:
		return night ? "night" : "clear";
	case 116:
		return night ? "partly-night" : "partly";
	case 119: case 122:
		return "cloudy";
	case 143: case 248: case 260:
		return "fog";
	case 200: case 386: case 389: case 392: case 395:
		return code >= 392 ? "snow" : "thunder";
	case 179: case 227: case 230: case 323: case 326: case 329: case 332:
	case 335: case 338: case 368: case 371: case 350: case 374: case 377:
		return "snow";
	case 182: case 185: case 281: case 284: case 311: case 314: case 317:
	case 320: case 362: case 365:
		return "sleet";
	default:
		return "rain";
	}
}

/* Whether the sun is down now, from "06:45 AM" style times of the day */
static bool weather_night(struct json *day) {
	struct json *astro = json_at(json_get(day, "astronomy"), 0);
	struct tm rise = { 0 }, set_ = { 0 };
	if (strptime(json_str(json_get(astro, "sunrise"), ""), "%I:%M %p", &rise) == NULL ||
			strptime(json_str(json_get(astro, "sunset"), ""), "%I:%M %p", &set_) == NULL) {
		return false;
	}
	time_t t = time(NULL);
	struct tm now;
	localtime_r(&t, &now);
	int m = now.tm_hour * 60 + now.tm_min;
	return m < rise.tm_hour * 60 + rise.tm_min ||
		m >= set_.tm_hour * 60 + set_.tm_min;
}

static void weather_content(struct widget *w, struct content *c) {
	struct weather *wt = w->data;
	if (wt->data == NULL) {
		set(c, "heading", "fetching…");
		set(c, "label", "Weather");
		return;
	}
	struct json *now = json_at(json_get(wt->data, "current_condition"), 0);
	struct json *area = json_at(json_get(wt->data, "nearest_area"), 0);
	struct json *days = json_get(wt->data, "weather");
	set(c, "template", "forecast");
	set(c, "glyph", "%s", weather_glyph(atoi(json_str(json_get(now, "weatherCode"), "0")),
		weather_night(json_at(days, 0))));
	set(c, "block", "%s°", json_str(json_get(now, "temp_C"), "?"));
	set(c, "text1", "%s", nested_value(now, "weatherDesc"));
	set(c, "text2", "Feels like %s°", json_str(json_get(now, "FeelsLikeC"), "?"));
	set(c, "text3", "Humidity\t%s%%", json_str(json_get(now, "humidity"), "?"));
	set(c, "text4", "Wind\t%s %s",
		json_str(json_get(now, wt->mph ? "windspeedMiles" : "windspeedKmph"),
			"?"), wt->mph ? "mph" : "km/h");
	/* Today and the days after, in columns */
	for (int i = 0; i < 3 && i < json_length(days); i++) {
		struct json *day = json_at(days, i);
		GDate date;
		g_date_clear(&date, 1);
		g_date_set_parse(&date, json_str(json_get(day, "date"), ""));
		char name[16] = "";
		if (i == 0) {
			snprintf(name, sizeof(name), "Today");
		} else if (g_date_valid(&date)) {
			g_date_strftime(name, sizeof(name), "%a", &date);
		}
		struct json *noon = json_at(json_get(day, "hourly"), 4);
		char key[32];
		snprintf(key, sizeof(key), "day%d", i + 1);
		set(c, key, "%s", name);
		snprintf(key, sizeof(key), "glyph%d", i + 1);
		set(c, key, "%s", weather_glyph(atoi(json_str(json_get(noon, "weatherCode"),
			"0")), false));
		snprintf(key, sizeof(key), "value%d", i + 1);
		set(c, key, "%s°", json_str(json_get(day, "maxtempC"), "?"));
		snprintf(key, sizeof(key), "low%d", i + 1);
		set(c, key, "%s°", json_str(json_get(day, "mintempC"), "?"));
	}
	char updated[16];
	clock_format(updated, sizeof(updated), localtime(&wt->fetched),
		clock_mode(), true);
	/* wttr.in's nearest place: a made-up town in stealth mode */
	const char *place = nested_value(area, "areaName");
	if (place && place[0]) {
		place = c8_stealth_alias(C8_STEALTH_PLACE, place);
	}
	set(c, "label", "%s", place);
	set(c, "wide.label", "%s  ·  %s", place, updated);
	set(c, "large.label", "%s  ·  %s", place, updated);
}

static bool weather_init(struct widget *w, int argc, char **argv) {
	struct weather *wt = g_new0(struct weather, 1);
	const char *location = "";
	wt->mph = true;
	for (int i = 1; i + 1 < argc; i += 2) {
		if (strcmp(argv[i], "--location") == 0) {
			location = argv[i + 1];
		} else if (strcmp(argv[i], "--wind") == 0) {
			wt->mph = strcmp(argv[i + 1], "kmh") != 0 &&
				strcmp(argv[i + 1], "km/h") != 0;
		} else {
			return false;
		}
	}
	char *escaped = g_uri_escape_string(location, NULL, FALSE);
	wt->url = g_strdup_printf("https://wttr.in/%s?format=j1", escaped);
	char *name = g_strdup_printf("weather-%08x.json", g_str_hash(location));
	wt->file = cache_path(name);
	g_free(name);
	g_free(escaped);
	w->data = wt;
	return true;
}

const struct widget_kind kind_weather = {
	.name = "weather",
	.summary = "Weather now, today and the next days, from wttr.in",
	.options = "              --location PLACE   default: wttr.in guesses from your address\n"
		"              --wind mph|kmh     default mph\n",
	.tick_ms = 60000,
	.init = weather_init,
	.tick = weather_tick,
	.content = weather_content,
};
