/*
 * Night light: the screens go warmer in the evening, [nightlight] in
 * config.ini. Each display's gamma ramps are scaled towards the white of
 * `temperature` kelvin, by how far the schedule says (it eases in and out
 * over RAMP_MIN minutes at its ends, and over a second when switched by
 * hand).
 *
 * The shell's quick tile is "warm now": against the schedule it holds
 * only until the schedule next turns (`forced`), so a tile pressed at
 * noon doesn't leave the screens warm for good.
 *
 * A gamma-control client (gammastep, wlsunset) setting a display's
 * ramps has that display to itself until it lets go.
 */
#define _GNU_SOURCE
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <wlr/render/color.h>
#include <wlr/types/wlr_output.h>
#include <wlr/util/log.h>
#include "server.h"

#define RAMP_MIN 30 // minutes the schedule takes to go all the way
#define FADE_MS 50 // between steps of a change
#define FADE_STEP 0.05 // of the way a step: a second for all of it
#define CHECK_MS 30000 // between looks at the clock

static struct {
	struct wl_event_source *timer;
	double shown; // 0 = as the screens are, 1 = all the way warm
	bool inside; // the schedule's hours, as last looked
	bool forced, forced_on; // the tile, against the schedule
	bool told_on; // what the shell was told last
	int logged; // the last strength logged, in percent, -1 for none
} nl = { .logged = -1 };

/* Minutes into today, local time; C8_NIGHT_NOW=HH:MM for tests */
static int now_minutes(struct tm *tm) {
	time_t t = time(NULL);
	localtime_r(&t, tm);
	const char *fake = getenv("C8_NIGHT_NOW");
	int h, m;
	if (fake && sscanf(fake, "%d:%d", &h, &m) == 2) {
		return (h * 60 + m) % 1440;
	}
	return tm->tm_hour * 60 + tm->tm_min;
}

/*
 * Sunset and sunrise in local minutes of today (NOAA's short form, good
 * to a couple of minutes). False where the sun doesn't cross the
 * horizon today: *from is then 0 for a day without sun, -1 with nothing
 * but.
 */
static bool sun_times(const struct tm *tm, double lat, double lon,
		int *from, int *to) {
	double g = 2 * M_PI / 365 * tm->tm_yday;
	double eq = 229.18 * (0.000075 + 0.001868 * cos(g) - 0.032077 * sin(g) -
		0.014615 * cos(2 * g) - 0.040849 * sin(2 * g));
	double decl = 0.006918 - 0.399912 * cos(g) + 0.070257 * sin(g) -
		0.006758 * cos(2 * g) + 0.000907 * sin(2 * g) -
		0.002697 * cos(3 * g) + 0.00148 * sin(3 * g);
	double rlat = lat * M_PI / 180;
	double c = cos(90.833 * M_PI / 180) / (cos(rlat) * cos(decl)) -
		tan(rlat) * tan(decl);
	if (c > 1 || c < -1) {
		*from = c > 1 ? 0 : -1;
		return false;
	}
	double ha = acos(c) * 180 / M_PI;
	double zone = tm->tm_gmtoff / 60.0;
	int rise = (int)lround(720 - 4 * (lon + ha) - eq + zone);
	int set = (int)lround(720 - 4 * (lon - ha) - eq + zone);
	*from = ((set % 1440) + 1440) % 1440;
	*to = ((rise % 1440) + 1440) % 1440;
	return true;
}

/* How warm the schedule says to be now, 0 to 1 */
static double scheduled(struct c8_server *server) {
	struct c8_config *c = &server->config;
	if (c->night.schedule == C8_NIGHT_ALWAYS) {
		return 1;
	}
	struct tm tm;
	int now = now_minutes(&tm);
	int from = c->night.from, to = c->night.to;
	if (c->night.schedule == C8_NIGHT_SUNSET && c->night.has_place &&
			!sun_times(&tm, c->night.latitude, c->night.longitude,
				&from, &to)) {
		return from == 0 ? 1 : 0;
	}
	int length = ((to - from) % 1440 + 1440) % 1440;
	int in = ((now - from) % 1440 + 1440) % 1440;
	if (length == 0 || in >= length) {
		return 0;
	}
	/* A minute in counts, so the first look inside already shows */
	double up = (in + 1) / (double)RAMP_MIN;
	double down = (length - in) / (double)RAMP_MIN;
	double s = up < down ? up : down;
	return s > 1 ? 1 : s;
}

static double target(struct c8_server *server) {
	if (nl.forced) {
		return nl.forced_on ? 1 : 0;
	}
	return server->config.night.enabled ? scheduled(server) : 0;
}

bool c8_nightlight_on(struct c8_server *server) {
	return target(server) > 0;
}

/* The white of a black body at `kelvin`, as what to multiply red, green
 * and blue by (Tanner Helland's fit, fine from 1000 to 6500 K) */
static void white(int kelvin, double rgb[static 3]) {
	double t = kelvin / 100.0;
	rgb[0] = 1;
	rgb[1] = (99.4708025861 * log(t) - 161.1195681661) / 255;
	rgb[2] = t <= 19 ? 0 : (138.5177312231 * log(t - 10) - 305.0447927307) / 255;
	for (int i = 1; i < 3; i++) {
		rgb[i] = rgb[i] < 0 ? 0 : rgb[i] > 1 ? 1 : rgb[i];
	}
}

/* What a display shows now, as one number to tell a change by */
static int key_now(struct c8_server *server) {
	int permille = (int)lround(nl.shown * 1000);
	return permille ? server->config.night.temperature * 1024 + permille : 0;
}

static void apply_output(struct c8_output *output) {
	struct c8_server *server = output->server;
	struct wlr_output *wlr_output = output->wlr_output;
	int key = key_now(server);
	if (output->gamma_client || output->night_key == key ||
			!wlr_output->enabled) {
		return;
	}
	size_t size = wlr_output_get_gamma_size(wlr_output);
	if (size < 2) {
		return; // headless, nested: no ramps to set
	}
	struct wlr_color_transform *tr = NULL;
	if (key) {
		double rgb[3];
		white(server->config.night.temperature, rgb);
		uint16_t *ramps = malloc(3 * size * sizeof(uint16_t));
		if (ramps == NULL) {
			return;
		}
		for (int ch = 0; ch < 3; ch++) {
			double by = 1 + (rgb[ch] - 1) * nl.shown;
			for (size_t i = 0; i < size; i++) {
				ramps[ch * size + i] = (uint16_t)lround(
					65535.0 * i / (size - 1) * by);
			}
		}
		tr = wlr_color_transform_init_lut_3x1d(size, ramps,
			ramps + size, ramps + 2 * size);
		free(ramps);
		if (tr == NULL) {
			return;
		}
	}
	struct wlr_output_state state;
	wlr_output_state_init(&state);
	wlr_output_state_set_color_transform(&state, tr);
	if (wlr_output_commit_state(wlr_output, &state)) {
		output->night_key = key;
	} else if (!output->night_failed) {
		output->night_failed = true; // said once, tried again each change
		wlr_log(WLR_ERROR, "Night light: %s didn't take the colours",
			wlr_output->name);
	}
	wlr_output_state_finish(&state);
	if (tr) {
		wlr_color_transform_unref(tr);
	}
}

void c8_nightlight_outputs(struct c8_server *server) {
	struct c8_output *output;
	wl_list_for_each(output, &server->outputs, link) {
		apply_output(output);
	}
}

void c8_nightlight_gamma_client(struct c8_server *server,
		struct wlr_output *wlr_output, bool has) {
	struct c8_output *output;
	wl_list_for_each(output, &server->outputs, link) {
		if (output->wlr_output != wlr_output) {
			continue;
		}
		output->gamma_client = has;
		output->night_key = 0; // theirs, or theirs just taken off
		if (!has) {
			apply_output(output);
		}
	}
}

static int tick(void *data) {
	struct c8_server *server = data;
	bool inside = scheduled(server) > 0;
	if (inside != nl.inside) {
		nl.inside = inside;
		nl.forced = false; // held only until the schedule turns
	}
	double want = target(server);
	double step = want - nl.shown;
	if (fabs(step) > FADE_STEP) {
		nl.shown += step > 0 ? FADE_STEP : -FADE_STEP;
	} else {
		nl.shown = want;
	}
	c8_nightlight_outputs(server);

	bool on = want > 0;
	if (on != nl.told_on) {
		nl.told_on = on;
		c8_shell_appearance_changed(server);
	}
	bool settled = nl.shown == want;
	int percent = (int)lround(want * 100);
	if (settled && percent != nl.logged) {
		nl.logged = percent;
		wlr_log(WLR_INFO, "Night light: %d K at %d%%",
			server->config.night.temperature, percent);
	}
	wl_event_source_timer_update(nl.timer, settled ? CHECK_MS : FADE_MS);
	return 0;
}

/* Said once for each place: the one thing here nobody can check by eye */
static void log_sun(struct c8_server *server) {
	struct c8_config *c = &server->config;
	struct tm tm;
	int from, to;
	if (c->night.schedule != C8_NIGHT_SUNSET || !c->night.has_place) {
		return;
	}
	now_minutes(&tm);
	if (sun_times(&tm, c->night.latitude, c->night.longitude, &from, &to)) {
		wlr_log(WLR_INFO, "Night light: sunset %02d:%02d, sunrise %02d:%02d "
			"at %g, %g", from / 60, from % 60, to / 60, to % 60,
			c->night.latitude, c->night.longitude);
	}
}

/* [nightlight] changed (PC settings, config.ini by hand) */
void c8_nightlight_configure(struct c8_server *server) {
	nl.forced = false;
	log_sun(server);
	nl.inside = scheduled(server) > 0;
	if (nl.timer) {
		tick(server);
	}
}

/* The quick tile and the night-light binding: warm now, or not */
void c8_nightlight_set(struct c8_server *server, bool on) {
	struct c8_config *c = &server->config;
	if (on == c8_nightlight_on(server)) {
		return;
	}
	if (!c->night.enabled) {
		/* Saved, so it's on from here; now too if it's the day */
		c8_settings_set(server, "nightlight", "enabled", "true");
	} else if (c->night.schedule == C8_NIGHT_ALWAYS) {
		c8_settings_set(server, "nightlight", "enabled", "false");
	}
	nl.inside = scheduled(server) > 0;
	bool by_schedule = server->config.night.enabled && nl.inside;
	nl.forced = on != by_schedule;
	nl.forced_on = on;
	tick(server);
}

void c8_nightlight_toggle(struct c8_server *server) {
	c8_nightlight_set(server, !c8_nightlight_on(server));
}

void c8_nightlight_init(struct c8_server *server) {
	nl.timer = wl_event_loop_add_timer(server->loop, tick, server);
	nl.inside = scheduled(server) > 0;
	/* Straight to where it should be: no fade at login */
	nl.shown = target(server);
	nl.told_on = nl.shown > 0;
	log_sun(server);
	tick(server);
}

void c8_nightlight_finish(struct c8_server *server) {
	if (nl.timer) {
		wl_event_source_remove(nl.timer);
		nl.timer = NULL;
	}
}
