export function withSelectedResource(resources, value) {
    const selectedId = Number(value || 0);
    if (!selectedId || resources.some((resource) => Number(resource.resourceId) === selectedId)) {
        return resources;
    }
    return [{ resourceId: selectedId, name: `资源 #${selectedId}` }, ...resources];
}

export function levelBadgeResourcesForTrack(resources, track) {
    return (resources || []).filter((resource) => {
        const metadata = resourceMetadata(resource);
        return (
            (resource.badgeForm || metadata.badgeForm) === "strip" &&
            (resource.badgeKind || metadata.badgeKind) === "level" &&
            (resource.levelTrack || metadata.levelTrack) === track
        );
    });
}

export function levelShortBadgeResourcesForTrack(resources, track) {
    return (resources || []).filter((resource) => {
        const metadata = resourceMetadata(resource);
        return (
            (resource.badgeForm || metadata.badgeForm) === "tile" &&
            (resource.badgeKind || metadata.badgeKind) === "level" &&
            (resource.levelTrack || metadata.levelTrack) === track
        );
    });
}

export function levelAvatarFrameResourcesForTrack(resources, track) {
    return (resources || []).filter((resource) => {
        const metadata = resourceMetadata(resource);
        return (
            resource.resourceType === "avatar_frame" &&
            (resource.avatarFrameKind || metadata.avatarFrameKind) === "level" &&
            (resource.levelTrack || metadata.levelTrack) === track
        );
    });
}

function resourceMetadata(resource) {
    try {
        const metadata = JSON.parse(resource?.metadataJson || "{}");
        return {
            avatarFrameKind: String(metadata.avatar_frame_kind || "")
                .trim()
                .toLowerCase(),
            badgeForm: String(metadata.badge_form || "")
                .trim()
                .toLowerCase(),
            badgeKind: String(metadata.badge_kind || "")
                .trim()
                .toLowerCase(),
            levelTrack: String(metadata.level_track || "")
                .trim()
                .toLowerCase(),
        };
    } catch {
        return {};
    }
}
