//
// Main loop. Pulls input, handles resizes, dispatches to the current view,
// swaps buffers.
//

run_main_loop :: () {
    while !app.quit {
        tick_time();

        Input.update_window_events();

        for Input.get_window_resizes() {
            Simp.update_window(it.window);
            if it.window == app.window {
                resized := (it.width != app.window_width) || (it.height != app.window_height);
                app.window_width  = it.width;
                app.window_height = it.height;
                if resized init_fonts();
            }
        }

        for event: Input.events_this_frame {
            if event.type == .QUIT then app.quit = true;
            getrect_handle_event(event);
        }

        http_pump();   // fire callbacks for any HTTP requests that finished since last frame
        image_pump();  // hand queued image fetches to http_submit, up to the concurrency cap

        if app.audio_inited  Sound.set_master_volume(app.master_volume);

        draw_one_frame();

        if app.audio_inited Sound.update();

        // Auto-advance once the active stream has finished.
        if app.track_finished {
            app.track_finished = false;
            queue_next();
        }

        reset_temporary_storage();
        sleep_milliseconds(8);
    }
}

draw_one_frame :: () {
    app.theme = player_theme();
    set_default_theme(app.theme);

    bg := app.theme.background_color;
    Simp.clear_render_target(bg.x, bg.y, bg.z, 1);

    x, y, w, h := get_dimensions(app.window, true);
    ui_per_frame_update(app.window, w, h, app.current_time);

    // Library: visualizer behind the UI. Now-playing: visualizer is drawn
    // inside draw_now_playing_view, after the backdrop, so bars sit on top.
    if app.current_view == .LIBRARY {
        gfx_draw_visualizer_background(xx w, xx h);
    }

    if #complete app.current_view == {
        case .LOGIN;        draw_login_view();
        case .LIBRARY;      draw_library_view();
        case .NOW_PLAYING;  draw_now_playing_view();
    }

    draw_popups();
    Simp.swap_buffers(app.window);
}
