use frienderer::{DrawCommand, RRect, Renderer};
use glam::{Vec4, ivec2, vec2};
use glfw::{Action, Context, Key, OpenGlProfileHint, WindowHint};

fn main() {
	let mut glfw = glfw::init(glfw::fail_on_errors).unwrap();
	glfw.window_hint(WindowHint::ContextVersion(3, 3));
	glfw.window_hint(WindowHint::OpenGlProfile(OpenGlProfileHint::Core));
	glfw.window_hint(WindowHint::Resizable(false));
	glfw.window_hint(WindowHint::TransparentFramebuffer(true));

	let (mut window, events) = glfw
		.create_window(500, 500, "frienderer - Rounded Rects", glfw::WindowMode::Windowed)
		.expect("Failed to create GLFW window.");

	window.set_key_polling(true);
	window.make_current();

	let (width, height) = window.get_size();
	let scale_factor = window.get_content_scale().0;
	let viewport = ivec2(width, height).as_vec2() / scale_factor;

	let mut renderer = Renderer::new_with_str_loader(viewport, scale_factor, true, |symbol| {
		(window.get_proc_address(symbol))
			.map(|f| f as *const _)
			.unwrap_or_default()
	});
	renderer.set_clear_color(0.0, 0.0, 0.0, 0.5);

	while !window.should_close() {
		glfw.poll_events();
		for (_, event) in glfw::flush_messages(&events) {
			#[allow(clippy::single_match)]
			match event {
				glfw::WindowEvent::Key(Key::Escape, _, Action::Press, _) => window.set_should_close(true),
				_ => {}
			}
		}

		let (width, height) = window.get_size();
		renderer.resize(
			((width as f32) * scale_factor) as i32,
			((height as f32) * scale_factor) as i32,
			scale_factor,
		);

		// Draw rectangles
		{
			let size = vec2(50.0, 50.0);
			let radius = 10.0;
			let border_width = 4.0;

			for i in 1..10 {
				let size = size + i as f32 * 2.0 * border_width;
				let radius = radius + border_width * i as f32;

				let color = if i % 2 == 0 { 0xff6464ff } else { 0xffffffff };
				renderer.push_draw_command(DrawCommand::RRect(RRect {
					pos: viewport / 2.0 - size / 2.0,
					size,
					border_radius: Vec4::splat(radius),
					border_width: Vec4::splat(border_width),
					fill_color: 0,
					stroke_color: color,
					box_blur: 0.0,
				}));
			}
		}

		renderer.draw();

		window.swap_buffers();
	}
}
