package ru.yandex.direct.web.entity.banner.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ru.yandex.direct.core.entity.image.container.UploadedToMdsImageInformation;
import ru.yandex.direct.core.entity.image.service.ImageService;
import ru.yandex.direct.result.Result;
import ru.yandex.direct.validation.result.Defect;
import ru.yandex.direct.validation.result.ValidationResult;
import ru.yandex.direct.web.core.entity.banner.service.validation.BannerImageValidationService;
import ru.yandex.direct.web.core.model.WebResponse;
import ru.yandex.direct.web.core.security.DirectWebAuthenticationSource;
import ru.yandex.direct.web.entity.banner.model.TextBannerImageUploadByUrlResponse;
import ru.yandex.direct.web.validation.kernel.ValidationResultConversionService;

import static ru.yandex.direct.core.validation.ValidationUtils.hasValidationIssues;
import static ru.yandex.direct.web.core.entity.banner.converter.BannerImageConverter.toWebUploadedToMdsFile;

@Service
public class TextBannerImageWebService {
    private final DirectWebAuthenticationSource authenticationSource;
    private final BannerImageValidationService textBannerImageValidationService;
    private final ValidationResultConversionService validationResultConversionService;
    private final ImageService bannerImageService;

    @Autowired
    public TextBannerImageWebService(DirectWebAuthenticationSource authenticationSource,
                                     BannerImageValidationService textBannerImageValidationService,
                                     ValidationResultConversionService validationResultConversionService,
                                     ImageService bannerImageService) {
        this.authenticationSource = authenticationSource;
        this.textBannerImageValidationService = textBannerImageValidationService;
        this.validationResultConversionService = validationResultConversionService;
        this.bannerImageService = bannerImageService;
    }

    public WebResponse saveImage(String url) {
        ValidationResult<String, Defect> validation = textBannerImageValidationService.validateImageUrl(url);
        if (validation.hasAnyErrors()) {
            return validationResultConversionService.buildValidationResponse(validation);
        }

        Result<UploadedToMdsImageInformation> operationResult = bannerImageService
                .saveImageFromUrlToMds(authenticationSource.getAuthentication().getSubjectUser().getClientId(), url);

        if (hasValidationIssues(operationResult)) {
            return validationResultConversionService.buildValidationResponse(operationResult);
        }

        return new TextBannerImageUploadByUrlResponse()
                .withResult(toWebUploadedToMdsFile(operationResult.getResult()));

    }
}
