use frienderer::{DrawCommand, RRect, Renderer};
use glam::{Vec2, Vec4, ivec2};
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(250, 180, "frienderer - 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 mut pos = ivec2(40, 40);
			for width in 0..=5 {
				pos.x = 40;
				for n in 1..=10 {
					let size = n + width * 2;

					renderer.push_draw_commands(&[DrawCommand::RRect(RRect {
						pos: pos.as_vec2(),
						size: Vec2::splat(size as f32),
						border_radius: Vec4::ZERO,
						border_width: Vec4::splat(width as f32),
						fill_color: 0xcc6464ff,
						stroke_color: 0xffffffff,
						box_blur: 0.0,
					})]);

					pos.x += size + 2;
				}
				pos.y += 12 + width * 2;
			}
		}

		renderer.draw();

		window.swap_buffers();
	}
}
