package app.mealsmadeeasy.api.image.converter;

import app.mealsmadeeasy.api.image.Image;
import app.mealsmadeeasy.api.image.view.ImageView;
import app.mealsmadeeasy.api.user.User;
import app.mealsmadeeasy.api.user.view.UserInfoView;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.stream.Collectors;

@Component
public class ImageToViewConverter {

    private final String baseUrl;

    public ImageToViewConverter(@Value("${app.mealsmadeeasy.api.baseUrl}") String baseUrl) {
        this.baseUrl = baseUrl;
    }

    private String getImageUrl(Image image) {
        return this.baseUrl + "/images/" + image.getOwner().getUsername() + "/" + image.getUserFilename();
    }

    @Contract("null, _, _ -> null")
    public @Nullable ImageView convert(@Nullable Image image, @Nullable User viewer, boolean includeViewers) {
        if (image == null) {
            return null;
        }
        final var builder = ImageView.builder()
                .url(this.getImageUrl(image))
                .created(image.getCreated())
                .modified(image.getModified())
                .filename(image.getUserFilename())
                .mimeType(image.getMimeType())
                .alt(image.getAlt())
                .caption(image.getCaption())
                .owner(UserInfoView.from(image.getOwner()))
                .isPublic(image.getIsPublic())
                .height(image.getHeight())
                .width(image.getWidth());
        if (includeViewers) {
            builder.viewers(
                    image.getViewers().stream()
                            .map(UserInfoView::from)
                            .collect(Collectors.toSet())
            );
        }
        return builder.build();
    }

}
