/* The Start background's pattern, shared with the lock screen */
#define _GNU_SOURCE
#include <math.h>
#include <string.h>
#include <c8ui/c8ui.h>
#include "pattern.h"
#include "pixels.h"

void c8_draw_pattern(cairo_t *cr, int w, int h, uint32_t bg,
		const char *pattern) {
	c8ui_set_source(cr, bg, 1);
	cairo_paint(cr);
	uint32_t fg = c8ui_shade(bg, 1.35);
	pattern = pattern ? pattern : "circles";
	if (strcmp(pattern, "circles") == 0) {
		/* Big overlapping rings drifting across the screen */
		for (int i = 0; i < 9; i++) {
			double cx = w * (0.08 + 0.13 * i);
			double cy = h * (i % 2 ? 0.85 : 0.2) + (i % 3) * h * 0.12;
			double r = h * (0.25 + 0.09 * (i % 4));
			c8ui_set_source(cr, fg, 0.18 + 0.05 * (i % 3));
			cairo_set_line_width(cr, h * (0.02 + 0.015 * (i % 3)));
			cairo_arc(cr, cx, cy, r, 0, 2 * M_PI);
			cairo_stroke(cr);
		}
	} else if (strcmp(pattern, "lines") == 0) {
		c8ui_set_source(cr, fg, 0.25);
		cairo_set_line_width(cr, 18);
		for (int x = -h; x < w; x += 64) {
			cairo_move_to(cr, x, h);
			cairo_line_to(cr, x + h, 0);
		}
		cairo_stroke(cr);
	} else if (strcmp(pattern, "squares") == 0) {
		for (int y = 0, row = 0; y < h + 120; y += 120, row++) {
			for (int x = (row % 2) * 60; x < w + 120; x += 120) {
				int k = (x / 120 * 7 + row * 3) % 5;
				c8ui_set_source(cr, fg, 0.12 + 0.06 * k);
				cairo_save(cr);
				cairo_translate(cr, x, y);
				cairo_rotate(cr, M_PI / 4);
				cairo_rectangle(cr, -34, -34, 68, 68);
				cairo_restore(cr);
				cairo_fill(cr);
			}
		}
	}
}

/* The picture chosen in Photos, scaled to cover the screen, its middle
 * kept. Read each time the background is drawn again, which is only
 * when the size, the appearance or the picture changes. */
bool c8_draw_picture(cairo_t *cr, int w, int h, enum c8_background which) {
	char *path = c8_background_path(which);
	cairo_surface_t *img = image_from_pixbuf(
		gdk_pixbuf_new_from_file(path, NULL));
	g_free(path);
	if (img == NULL) {
		return false;
	}
	int iw = cairo_image_surface_get_width(img);
	int ih = cairo_image_surface_get_height(img);
	double s = fmax((double)w / iw, (double)h / ih);
	cairo_save(cr);
	cairo_rectangle(cr, 0, 0, w, h);
	cairo_clip(cr);
	cairo_translate(cr, (w - iw * s) / 2, (h - ih * s) / 2);
	cairo_scale(cr, s, s);
	cairo_set_source_surface(cr, img, 0, 0);
	cairo_pattern_set_filter(cairo_get_source(cr), CAIRO_FILTER_GOOD);
	cairo_paint(cr);
	cairo_restore(cr);
	cairo_surface_destroy(img);
	return true;
}

void c8_draw_background(cairo_t *cr, int w, int h, uint32_t bg,
		const char *pattern, enum c8_background which) {
	if (!c8_draw_picture(cr, w, h, which)) {
		c8_draw_pattern(cr, w, h, bg, pattern);
	}
}
