package ru.yandex.canvas.model.validation.presetbased.creative;

import java.util.Optional;

import javax.annotation.Nonnull;

import org.checkerframework.checker.nullness.qual.NonNull;
import org.springframework.validation.Errors;

import ru.yandex.canvas.model.CreativeData;
import ru.yandex.canvas.model.File;
import ru.yandex.canvas.model.MediaSet;
import ru.yandex.canvas.model.elements.Element;
import ru.yandex.canvas.model.stillage.StillageFileInfo;
import ru.yandex.canvas.model.validation.FileServiceContainer;
import ru.yandex.canvas.service.FileService;

// FIXME: https://st.yandex-team.ru/BANNERSTORAGE-5082
public class ImageFileSizeValidator extends MediaSetValidator<Element> implements FileServiceContainer {

    public static final String MESSAGE = "{image_too_big}";

    private FileService fileService;

    @NonNull
    private Integer maxFileSize;

    public ImageFileSizeValidator() {
    }

    public ImageFileSizeValidator(@NonNull Integer maxFileSize) {
        this.maxFileSize = maxFileSize;
    }

    @Nonnull
    public Integer getMaxFileSize() {
        return maxFileSize;
    }

    public void setMaxFileSize(Integer maxFileSize) {
        this.maxFileSize = maxFileSize;
    }

    @Override
    public void setFileService(FileService fileService) {
        this.fileService = fileService;
    }

    @Override
    protected void validate(Element element, MediaSet mediaSet, CreativeData creativeData, @NonNull Errors errors) {
        for (String fileId : getFileIds(mediaSet)) {
            Optional<StillageFileInfo> fileInfo =
                    fileService.getByIdInternal(fileId).map(File::getStillageFileInfo);

            if (fileInfo.isEmpty() || fileInfo.get().getFileSize() > maxFileSize) {
                errors.rejectValue(null, "file_size", MESSAGE);
                return;
            }
        }
    }
}
