use std::sync::Arc;

use libremetaverse::imaging::Targa;
use libremetaverse::{GridClient, Inventory, InventoryItem};
use libremetaverse_types::{AssetType, UUID};

#[test]
fn root_inventory_updates_preserve_link_index() {
    let client = Arc::new(GridClient::new().expect("offline client"));
    let inventory = Inventory::new_with_grid_client_uuid(client, UUID::zero()).expect("store");
    let item_id = UUID::new_with_u_int64(1).expect("item UUID");
    let first_target = UUID::new_with_u_int64(2).expect("first target");
    let second_target = UUID::new_with_u_int64(3).expect("second target");
    let mut item = InventoryItem::new_with_uuid(item_id).expect("item");
    item.set_asset_type(AssetType::Link);
    item.set_asset_uuid(first_target);
    inventory.update_node_for(&item).expect("insert root link");
    assert_eq!(inventory.find_all_links(first_target).unwrap().len(), 1);

    item.set_asset_uuid(second_target);
    inventory
        .update_node_for(&item)
        .expect("retarget root link");
    assert!(inventory.find_all_links(first_target).unwrap().is_empty());
    assert_eq!(inventory.find_all_links(second_target).unwrap().len(), 1);

    item.set_asset_type(AssetType::Texture);
    inventory.update_node_for(&item).expect("replace link");
    assert!(inventory.find_all_links(second_target).unwrap().is_empty());
    assert_eq!(inventory.count(), 1);
}

#[test]
fn borrowed_tga_fast_path_preserves_fixture_pixels() {
    let bytes = include_bytes!("../../../benchmarks/fixtures/image.tga");
    let image = Targa::decode_to_managed_image_with_bytes(bytes).expect("decode TGA fixture");
    assert_eq!((image.width, image.height), (128, 128));
    assert_eq!(image.red.len(), 128 * 128);
    assert_eq!(
        (&image.red[..4], &image.green[..4], &image.blue[..4]),
        (&[0, 1, 2, 3][..], &[0, 3, 6, 9][..], &[0, 7, 14, 21][..])
    );
    assert!(image.alpha.iter().all(|value| *value == u8::MAX));
}
