/*
 * Night light, at the foot of the Displays page: [nightlight] in
 * config.ini, which the compositor does (nightlight.c there).
 */
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <glib.h>
#include "settings.h"
#include "clock.h"

static const char *const schedule_values[] = { "times", "sunset", "always" };
static const char *const schedule_labels[] = { "Set hours",
	"Sunset to sunrise", "All the time" };

static struct {
	struct c8ui_widget *when; // what the schedule chosen needs
	struct c8ui_widget *from, *to;
	int shown; // the schedule `when` was built for, -1 for none
} night = { .shown = -1 };

static int schedule_index(void) {
	const char *now = setting_or("nightlight", "schedule", "times");
	for (int i = 0; i < 3; i++) {
		if (strcmp(now, schedule_values[i]) == 0) {
			return i;
		}
	}
	return 0;
}

static void read_time(const char *key, const char *def, int *h, int *m) {
	if (sscanf(setting_or("nightlight", key, def), "%d:%d", h, m) != 2) {
		sscanf(def, "%d:%d", h, m);
	}
}

static void time_changed(struct c8ui_widget *w, void *data) {
	int h, m;
	char value[8];
	c8ui_time_get(w, &h, &m);
	snprintf(value, sizeof(value), "%02d:%02d", h, m);
	setting_set("nightlight", data, value);
}

static struct c8ui_widget *time_new(const char *header, const char *key,
		const char *def) {
	int h, m;
	read_time(key, def, &h, &m);
	struct c8ui_widget *t = c8ui_time_new(header, h, m, time_changed,
		(void *)key);
	c8ui_time_set_24h(t, !clock_12h(setting("general", "clock")));
	c8ui_time_set_minute_step(t, 5);
	return t;
}

/* Weather's default place, "lat, lon", or NULL: the one place this PC
 * may already know */
static char *weather_place(void) {
	char *path = g_build_filename(g_get_user_config_dir(), "cont8nuum",
		"weather.ini", NULL);
	GKeyFile *kf = g_key_file_new();
	char *place = NULL;
	if (g_key_file_load_from_file(kf, path, G_KEY_FILE_NONE, NULL)) {
		char *home = g_key_file_get_string(kf, "weather", "home", NULL);
		char *group = home ? g_strdup_printf("place %s", home) : NULL;
		GError *e1 = NULL, *e2 = NULL;
		double lat = group ? g_key_file_get_double(kf, group, "lat", &e1) : 0;
		double lon = group ? g_key_file_get_double(kf, group, "lon", &e2) : 0;
		if (group && e1 == NULL && e2 == NULL) {
			char a[G_ASCII_DTOSTR_BUF_SIZE], b[G_ASCII_DTOSTR_BUF_SIZE];
			place = g_strdup_printf("%s, %s",
				g_ascii_formatd(a, sizeof(a), "%.2f", lat),
				g_ascii_formatd(b, sizeof(b), "%.2f", lon));
		}
		g_clear_error(&e1);
		g_clear_error(&e2);
		g_free(group);
		g_free(home);
	}
	g_key_file_free(kf);
	g_free(path);
	return place;
}

static void use_weather(struct c8ui_widget *w, void *data) {
	char *place = weather_place();
	if (place) {
		setting_set("nightlight", "place", place);
	}
	g_free(place);
}

static void build_when(void) {
	int schedule = schedule_index();
	if (night.when == NULL || schedule == night.shown) {
		return;
	}
	night.shown = schedule;
	c8ui_widget_clear(night.when);
	if (schedule == 0) {
		struct c8ui_widget *row = c8ui_box_new(C8UI_HORIZONTAL, 24);
		c8ui_box_set_narrow_orientation(row, C8UI_VERTICAL);
		c8ui_widget_track(time_new("Turn on at", "from", "21:00"),
			&night.from);
		c8ui_widget_track(time_new("Turn off at", "to", "07:00"),
			&night.to);
		add(row, night.from);
		add(row, night.to);
		add(night.when, row);
	} else if (schedule == 1) {
		if (c8_stealth()) { // the place is where the user is
			add(night.when, caption("Where you are is hidden in stealth "
				"mode. Turn it off to change it."));
		} else {
			add(night.when, bound_entry("nightlight", "place",
				"Where you are", "Latitude, longitude, as 47.6, -122.3"));
		}
		char *place = c8_stealth() ? NULL : weather_place();
		if (place) {
			add(night.when, c8ui_button_new("Use my place in Weather",
				use_weather, NULL));
		}
		g_free(place);
		add(night.when, caption("Sunset and sunrise are worked out on "
			"this PC from where you are; nothing is looked up. Until "
			"you say where, Night light keeps to its set hours."));
	}
}

static void night_gone(struct c8ui_widget *w, void *data) {
	if (night.when == w) {
		night.when = NULL;
		night.shown = -1;
	}
}

void night_refresh(void) {
	build_when();
	struct c8ui_widget *const pickers[] = { night.from, night.to };
	static const char *const keys[] = { "from", "to" };
	static const char *const defs[] = { "21:00", "07:00" };
	for (int i = 0; i < 2; i++) {
		if (pickers[i] && !pickers[i]->focused) {
			int h, m;
			read_time(keys[i], defs[i], &h, &m);
			c8ui_time_set(pickers[i], h, m);
		}
	}
}

void night_build(struct c8ui_widget *box) {
	add(box, section_title("Night light"));
	add(box, bound_toggle("nightlight", "enabled", "Night light",
		"Warmer colours in the evening, easier on the eyes. The Night "
		"light tile in the Settings charm turns it on or off for now.",
		false));
	struct c8ui_widget *warmth = bound_slider("nightlight", "temperature",
		"Colour at night", 1500, 6000, 100, 4000, "%.0f");
	c8ui_slider_set_format(warmth, "%.0f K");
	add(box, warmth);
	add(box, caption("Lower is warmer. Daylight is about 6500 K."));
	add(box, bound_choice("nightlight", "schedule", "When",
		schedule_values, schedule_labels, 3, 0));
	night.when = c8ui_box_new(C8UI_VERTICAL, 12);
	night.when->fill = true;
	night.when->on_destroy = night_gone;
	night.shown = -1;
	add(box, night.when);
	build_when();
}
