//
// Global shuffle — fetches all tracks (or all favourites) from the Jellyfin
// library and starts playing immediately. Uses the same Items_Response / Track
// parsing path as library browsing.
//

library_start_global_shuffle :: (mode: Shuffle_Mode) {
    req := New(Shuffle_Fetch);
    req.mode = mode;

    path: string;
    if mode == .FAVOURITES {
        path = tprint(
            "/Users/%/Items?IncludeItemTypes=Audio&Recursive=true&SortBy=SortName&Filters=IsFavorite&Limit=2000",
            app.jellyfin.user_id);
    } else {
        path = tprint(
            "/Users/%/Items?IncludeItemTypes=Audio&Recursive=true&SortBy=SortName&Limit=2000",
            app.jellyfin.user_id);
    }

    log_info("shuffle: fetching % tracks from library", ifx mode == .FAVOURITES then "favourite" else "all");
    http_submit("GET", path, on_done=on_shuffle_tracks_loaded, user_data=req);
}

#scope_file

Shuffle_Fetch :: struct {
    mode: Shuffle_Mode;
}

on_shuffle_tracks_loaded :: (task: *Http_Task) {
    req := cast(*Shuffle_Fetch) task.user_data;
    defer free(req);

    if !task.response.ok {
        log_error("shuffle fetch failed: status=%", task.response.status_code);
        return;
    }

    ok, parsed := Jaison.json_parse_string(task.response.body, Items_Response);
    if !ok {
        log_error("shuffle fetch: json parse failed");
        return;
    }

    if parsed.Items.count == 0 {
        log_warn("shuffle fetch: no tracks returned (mode=%)", req.mode);
        return;
    }

    queue.shuffle_mode = req.mode;
    queue_clear();
    for parsed.Items {
        t: Track;
        t.id             = copy_string(it.Id);
        t.name           = copy_string(it.Name);
        t.album          = copy_string(it.Album);
        t.album_id       = copy_string(it.AlbumId);
        t.artist         = copy_string(it.AlbumArtist);
        t.artist_id      = ifx it.AlbumArtists.count > 0
                           then copy_string(it.AlbumArtists[0].Id)
                           else copy_string(it.AlbumArtistId);
        t.duration_ticks = it.RunTimeTicks;
        t.index_number   = it.IndexNumber;
        t.is_favourite   = it.UserData.IsFavorite;
        queue_add(t);
    }

    queue_rebuild_shuffle();

    if queue.shuffle_order.count == 0 {
        log_warn("shuffle: no playable tracks after filtering");
        return;
    }

    queue.current = queue.shuffle_order[0];
    audio_play_track(queue.tracks[queue.current]);
    app.current_view = .NOW_PLAYING;

    log_info("shuffle: queued % tracks, starting '%'",
        queue.tracks.count, queue.tracks[queue.current].name);
}
