use sdl2::{
    event::Event, keyboard::Keycode, pixels::Color, render::WindowCanvas, EventPump, Sdl,
    VideoSubsystem,
};
use std::time::Duration;

pub struct Application {
    sdl_context: Sdl,
    video_subsystem: VideoSubsystem,
    event_pump: EventPump,
    main_window: WindowCanvas,
}

impl Application {
    pub fn new() -> Result<Self, Box<dyn std::error::Error>> {
        let new_sdl_context = sdl2::init()?;
        let new_video_subsystem = new_sdl_context.video()?;
        let new_event_subsystem = new_sdl_context.event_pump()?;

        let new_window = new_video_subsystem
            .window("Doom - Oxidized", 320, 240)
            .position_centered()
            .build()?;

        let window_surface = new_window.into_canvas().build()?;

        Ok(Self {
            sdl_context: new_sdl_context,
            video_subsystem: new_video_subsystem,
            event_pump: new_event_subsystem,
            main_window: window_surface,
        })
    }

    pub fn video_subsystem(&self) -> &VideoSubsystem {
        &self.video_subsystem
    }

    pub fn event_subsystem(&mut self) -> &mut EventPump {
        &mut self.event_pump
    }

    pub fn sdl_context(&self) -> &Sdl {
        &self.sdl_context
    }

    pub fn run(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        self.main_window.set_draw_color(Color::RGB(0, 255, 255));
        self.main_window.clear();
        self.main_window.present();

        let mut i = 0;
        'running: loop {
            i = (i + 1) % 255;
            self.main_window.set_draw_color(Color::RGB(i, 64, 255 - i));
            self.main_window.clear();

            for event in self.event_pump.poll_iter() {
                match event {
                    Event::Quit { .. }
                    | Event::KeyDown {
                        keycode: Some(Keycode::Escape),
                        ..
                    } => break 'running,
                    _ => {}
                }
            }

            self.main_window.present();
            ::std::thread::sleep(Duration::new(0, 1_000_000_000u32 / 30));
        }

        Ok(())
    }
}
