#include <assert.h>
#include <float.h>
#include <limits.h>
#include <stdlib.h>
#include <wlr/types/wlr_output_layout.h>
#include <wlr/types/wlr_output.h>
#include <wlr/util/box.h>
#include <wlr/util/log.h>

static const struct wlr_addon_interface addon_impl;

static void output_layout_handle_display_destroy(struct wl_listener *listener,
		void *data) {
	struct wlr_output_layout *layout = wl_container_of(listener, layout, display_destroy);
	wlr_output_layout_destroy(layout);
}

struct wlr_output_layout *wlr_output_layout_create(struct wl_display *display) {
	struct wlr_output_layout *layout = calloc(1, sizeof(*layout));
	if (layout == NULL) {
		return NULL;
	}
	wl_list_init(&layout->outputs);
	layout->display = display;

	wl_signal_init(&layout->events.add);
	wl_signal_init(&layout->events.change);
	wl_signal_init(&layout->events.destroy);

	layout->display_destroy.notify = output_layout_handle_display_destroy;
	wl_display_add_destroy_listener(display, &layout->display_destroy);

	return layout;
}

static void output_layout_output_destroy(
		struct wlr_output_layout_output *l_output) {
	wl_signal_emit_mutable(&l_output->events.destroy, l_output);
	wlr_output_destroy_global(l_output->output);
	wl_list_remove(&l_output->commit.link);
	wl_list_remove(&l_output->link);
	wlr_addon_finish(&l_output->addon);
	free(l_output);
}

void wlr_output_layout_destroy(struct wlr_output_layout *layout) {
	if (!layout) {
		return;
	}

	wl_signal_emit_mutable(&layout->events.destroy, layout);

	struct wlr_output_layout_output *l_output, *temp;
	wl_list_for_each_safe(l_output, temp, &layout->outputs, link) {
		output_layout_output_destroy(l_output);
	}

	wl_list_remove(&layout->display_destroy.link);
	free(layout);
}

static void output_layout_output_get_box(
		struct wlr_output_layout_output *l_output,
		struct wlr_box *box) {
	box->x = l_output->x;
	box->y = l_output->y;
	wlr_output_effective_resolution(l_output->output,
		&box->width, &box->height);
}

/**
 * This must be called whenever the layout changes to reconfigure the auto
 * configured outputs and emit the `changed` event.
 *
 * Auto configured outputs are placed to the right of the north east corner of
 * the rightmost output in the layout in a horizontal line.
 */
static void output_layout_reconfigure(struct wlr_output_layout *layout) {
	int max_x = INT_MIN;
	int max_x_y = INT_MIN; // y value for the max_x output

	// find the rightmost x coordinate occupied by a manually configured output
	// in the layout
	struct wlr_output_layout_output *l_output;
	struct wlr_box output_box;

	wl_list_for_each(l_output, &layout->outputs, link) {
		if (l_output->auto_configured) {
			continue;
		}

		output_layout_output_get_box(l_output, &output_box);
		if (output_box.x + output_box.width > max_x) {
			max_x = output_box.x + output_box.width;
			max_x_y = output_box.y;
		}
	}

	if (max_x == INT_MIN) {
		// there are no manually configured outputs
		max_x = 0;
		max_x_y = 0;
	}

	wl_list_for_each(l_output, &layout->outputs, link) {
		if (!l_output->auto_configured) {
			continue;
		}
		output_layout_output_get_box(l_output, &output_box);
		l_output->x = max_x;
		l_output->y = max_x_y;
		max_x += output_box.width;
	}

	wl_signal_emit_mutable(&layout->events.change, layout);
}

static void output_update_global(struct wlr_output_layout *layout,
		struct wlr_output *output) {
	// Don't expose the output if it doesn't have a current mode
	if (output->width > 0 && output->height > 0) {
		wlr_output_create_global(output, layout->display);
	} else {
		wlr_output_destroy_global(output);
	}
}

static void handle_output_commit(struct wl_listener *listener, void *data) {
	struct wlr_output_layout_output *l_output =
		wl_container_of(listener, l_output, commit);
	struct wlr_output_event_commit *event = data;

	if (event->state->committed & (WLR_OUTPUT_STATE_SCALE |
			WLR_OUTPUT_STATE_TRANSFORM |
			WLR_OUTPUT_STATE_MODE)) {
		output_layout_reconfigure(l_output->layout);
		output_update_global(l_output->layout, l_output->output);
	}
}

static void addon_destroy(struct wlr_addon *addon) {
	assert(addon->impl == &addon_impl);
	struct wlr_output_layout_output *l_output =
		wl_container_of(addon, l_output, addon);
	struct wlr_output_layout *layout = l_output->layout;
	output_layout_output_destroy(l_output);
	output_layout_reconfigure(layout);
}

static const struct wlr_addon_interface addon_impl = {
	.name = "wlr_output_layout_output",
	.destroy = addon_destroy,
};

static struct wlr_output_layout_output *output_layout_output_create(
		struct wlr_output_layout *layout, struct wlr_output *output) {
	struct wlr_output_layout_output *l_output = calloc(1, sizeof(*l_output));
	if (l_output == NULL) {
		return NULL;
	}
	l_output->layout = layout;
	l_output->output = output;
	wl_signal_init(&l_output->events.destroy);

	/*
	 * Insert at the end of the list so that auto-configuring the
	 * new output doesn't change the layout of other outputs
	 */
	wl_list_insert(layout->outputs.prev, &l_output->link);

	wl_signal_add(&output->events.commit, &l_output->commit);
	l_output->commit.notify = handle_output_commit;

	wlr_addon_init(&l_output->addon, &output->addons, layout, &addon_impl);

	return l_output;
}

static struct wlr_output_layout_output *output_layout_add(struct wlr_output_layout *layout,
		struct wlr_output *output, int lx, int ly,
		bool auto_configured) {
	struct wlr_output_layout_output *l_output =
		wlr_output_layout_get(layout, output);
	bool is_new = l_output == NULL;
	if (is_new) {
		l_output = output_layout_output_create(layout, output);
		if (l_output == NULL) {
			return NULL;
		}
	}

	l_output->x = lx;
	l_output->y = ly;
	l_output->auto_configured = auto_configured;

	output_layout_reconfigure(layout);
	output_update_global(layout, output);

	if (is_new) {
		wl_signal_emit_mutable(&layout->events.add, l_output);
	}

	return l_output;
}

struct wlr_output_layout_output *wlr_output_layout_add(struct wlr_output_layout *layout,
		struct wlr_output *output, int lx, int ly) {
	return output_layout_add(layout, output, lx, ly, false);
}

struct wlr_output_layout_output *wlr_output_layout_add_auto(struct wlr_output_layout *layout,
		struct wlr_output *output) {
	return output_layout_add(layout, output, 0, 0, true);
}

void wlr_output_layout_remove(struct wlr_output_layout *layout,
		struct wlr_output *output) {
	struct wlr_output_layout_output *l_output =
		wlr_output_layout_get(layout, output);
	if (l_output != NULL) {
		output_layout_output_destroy(l_output);
		output_layout_reconfigure(layout);
	}
}

struct wlr_output_layout_output *wlr_output_layout_get(
		struct wlr_output_layout *layout, struct wlr_output *reference) {
	struct wlr_output_layout_output *l_output = NULL;
	struct wlr_addon *addon =
		wlr_addon_find(&reference->addons, layout, &addon_impl);
	if (addon) {
		l_output = wl_container_of(addon, l_output, addon);
	}
	return l_output;
}

bool wlr_output_layout_contains_point(struct wlr_output_layout *layout,
		struct wlr_output *reference, int lx, int ly) {
	if (reference) {
		struct wlr_output_layout_output *l_output =
			wlr_output_layout_get(layout, reference);
		if (!l_output) {
			return false;
		}
		struct wlr_box output_box;
		output_layout_output_get_box(l_output, &output_box);
		return wlr_box_contains_point(&output_box, lx, ly);
	} else {
		return !!wlr_output_layout_output_at(layout, lx, ly);
	}
}

bool wlr_output_layout_intersects(struct wlr_output_layout *layout,
		struct wlr_output *reference, const struct wlr_box *target_lbox) {
	struct wlr_box out_box;

	if (reference == NULL) {
		struct wlr_output_layout_output *l_output;
		wl_list_for_each(l_output, &layout->outputs, link) {
			struct wlr_box output_box;
			output_layout_output_get_box(l_output, &output_box);
			if (wlr_box_intersection(&out_box, &output_box, target_lbox)) {
				return true;
			}
		}
		return false;
	} else {
		struct wlr_output_layout_output *l_output =
			wlr_output_layout_get(layout, reference);
		if (!l_output) {
			return false;
		}

		struct wlr_box output_box;
		output_layout_output_get_box(l_output, &output_box);
		return wlr_box_intersection(&out_box, &output_box, target_lbox);
	}
}

struct wlr_output *wlr_output_layout_output_at(struct wlr_output_layout *layout,
		double lx, double ly) {
	struct wlr_output_layout_output *l_output;
	wl_list_for_each(l_output, &layout->outputs, link) {
		struct wlr_box output_box;
		output_layout_output_get_box(l_output, &output_box);
		if (wlr_box_contains_point(&output_box, lx, ly)) {
			return l_output->output;
		}
	}
	return NULL;
}

void wlr_output_layout_output_coords(struct wlr_output_layout *layout,
		struct wlr_output *reference, double *lx, double *ly) {
	assert(layout && reference);
	double src_x = *lx;
	double src_y = *ly;

	struct wlr_output_layout_output *l_output;
	wl_list_for_each(l_output, &layout->outputs, link) {
		if (l_output->output == reference) {
			*lx = src_x - (double)l_output->x;
			*ly = src_y - (double)l_output->y;
			return;
		}
	}
}

void wlr_output_layout_closest_point(struct wlr_output_layout *layout,
		struct wlr_output *reference, double lx, double ly, double *dest_lx,
		double *dest_ly) {
	if (dest_lx == NULL && dest_ly == NULL) {
		return;
	}

	double min_x = lx, min_y = ly, min_distance = DBL_MAX;
	struct wlr_output_layout_output *l_output;
	wl_list_for_each(l_output, &layout->outputs, link) {
		if (reference != NULL && reference != l_output->output) {
			continue;
		}

		double output_x, output_y, output_distance;
		struct wlr_box output_box;
		output_layout_output_get_box(l_output, &output_box);
		wlr_box_closest_point(&output_box, lx, ly, &output_x, &output_y);

		// calculate squared distance suitable for comparison
		output_distance =
			(lx - output_x) * (lx - output_x) + (ly - output_y) * (ly - output_y);

		if (!isfinite(output_distance)) {
			output_distance = DBL_MAX;
		}

		if (output_distance < min_distance) {
			min_x = output_x;
			min_y = output_y;
			min_distance = output_distance;
		}
	}

	if (dest_lx) {
		*dest_lx = min_x;
	}
	if (dest_ly) {
		*dest_ly = min_y;
	}
}

void wlr_output_layout_get_box(struct wlr_output_layout *layout,
		struct wlr_output *reference, struct wlr_box *dest_box) {
	*dest_box = (struct wlr_box){0};

	struct wlr_output_layout_output *l_output;
	if (reference) {
		// output extents
		l_output = wlr_output_layout_get(layout, reference);

		if (l_output) {
			output_layout_output_get_box(l_output, dest_box);
		}
	} else {
		// layout extents
		int min_x = 0, max_x = 0, min_y = 0, max_y = 0;
		if (!wl_list_empty(&layout->outputs)) {
			min_x = min_y = INT_MAX;
			max_x = max_y = INT_MIN;
			wl_list_for_each(l_output, &layout->outputs, link) {
				struct wlr_box output_box;
				output_layout_output_get_box(l_output, &output_box);
				if (output_box.x < min_x) {
					min_x = output_box.x;
				}
				if (output_box.y < min_y) {
					min_y = output_box.y;
				}
				if (output_box.x + output_box.width > max_x) {
					max_x = output_box.x + output_box.width;
				}
				if (output_box.y + output_box.height > max_y) {
					max_y = output_box.y + output_box.height;
				}
			}
		}

		dest_box->x = min_x;
		dest_box->y = min_y;
		dest_box->width = max_x - min_x;
		dest_box->height = max_y - min_y;
	}
}

struct wlr_output *wlr_output_layout_get_center_output(
		struct wlr_output_layout *layout) {
	if (wl_list_empty(&layout->outputs)) {
		return NULL;
	}

	struct wlr_box extents;
	wlr_output_layout_get_box(layout, NULL, &extents);
	double center_x = extents.width / 2. + extents.x;
	double center_y = extents.height / 2. + extents.y;

	double dest_x = 0, dest_y = 0;
	wlr_output_layout_closest_point(layout, NULL, center_x, center_y,
		&dest_x, &dest_y);

	return wlr_output_layout_output_at(layout, dest_x, dest_y);
}

enum distance_selection_method {
	NEAREST,
	FARTHEST
};

static struct wlr_output *wlr_output_layout_output_in_direction(
		struct wlr_output_layout *layout, enum wlr_direction direction,
		struct wlr_output *reference, double ref_lx, double ref_ly,
		enum distance_selection_method distance_method) {
	assert(reference);

	struct wlr_box ref_box;
	wlr_output_layout_get_box(layout, reference, &ref_box);
	if (wlr_box_empty(&ref_box)) {
		// The output doesn't belong to the layout
		return NULL;
	}

	double min_distance = (distance_method == NEAREST) ? DBL_MAX : DBL_MIN;
	struct wlr_output *closest_output = NULL;
	struct wlr_output_layout_output *l_output;
	wl_list_for_each(l_output, &layout->outputs, link) {
		if (reference != NULL && reference == l_output->output) {
			continue;
		}

		struct wlr_box box;
		output_layout_output_get_box(l_output, &box);

		bool match = false;
		// test to make sure this output is in the given direction
		if (direction & WLR_DIRECTION_LEFT) {
			match = box.x + box.width <= ref_box.x || match;
		}
		if (direction & WLR_DIRECTION_RIGHT) {
			match = box.x >= ref_box.x + ref_box.width || match;
		}
		if (direction & WLR_DIRECTION_UP) {
			match = box.y + box.height <= ref_box.y || match;
		}
		if (direction & WLR_DIRECTION_DOWN) {
			match = box.y >= ref_box.y + ref_box.height || match;
		}
		if (!match) {
			continue;
		}

		// calculate distance from the given reference point
		double x, y;
		wlr_output_layout_closest_point(layout, l_output->output,
			ref_lx, ref_ly, &x, &y);
		double distance =
			(x - ref_lx) * (x - ref_lx) + (y - ref_ly) * (y - ref_ly);

		if ((distance_method == NEAREST)
				? distance < min_distance
				: distance > min_distance) {
			min_distance = distance;
			closest_output = l_output->output;
		}
	}
	return closest_output;
}

struct wlr_output *wlr_output_layout_adjacent_output(
		struct wlr_output_layout *layout, enum wlr_direction direction,
		struct wlr_output *reference, double ref_lx, double ref_ly) {
	return wlr_output_layout_output_in_direction(layout, direction,
			reference, ref_lx, ref_ly, NEAREST);
}

struct wlr_output *wlr_output_layout_farthest_output(
		struct wlr_output_layout *layout, enum wlr_direction direction,
		struct wlr_output *reference, double ref_lx, double ref_ly) {
	return wlr_output_layout_output_in_direction(layout, direction,
			reference, ref_lx, ref_ly, FARTHEST);
}
