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

import java.io.IOException;

import javax.annotation.ParametersAreNonnullByDefault;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import ru.yandex.direct.core.entity.freelancer.service.FreelancerClientAvatarService;
import ru.yandex.direct.result.Result;
import ru.yandex.direct.web.core.model.WebResponse;
import ru.yandex.direct.web.entity.freelancer.exception.FreelancerAvatarUploadException;
import ru.yandex.direct.web.entity.freelancer.model.FileDescription;
import ru.yandex.direct.web.entity.freelancer.model.FreelancerAvatarUploadResponse;
import ru.yandex.direct.web.validation.kernel.ValidationResultConversionService;

import static ru.yandex.direct.core.entity.freelancer.utils.ClientAvatarIdUtils.clientAvatarIdFromParams;

@Service
@ParametersAreNonnullByDefault
public class FreelancerAvatarWebService {
    private static final Long MAX_FILE_SIZE = 1024 * 1024 * 10L;

    private final FreelancerClientAvatarService freelancerClientAvatarService;
    private final ValidationResultConversionService validationResultConversionService;

    @Autowired
    public FreelancerAvatarWebService(FreelancerClientAvatarService freelancerClientAvatarService,
                                      ValidationResultConversionService validationResultConversionService) {
        this.freelancerClientAvatarService = freelancerClientAvatarService;
        this.validationResultConversionService = validationResultConversionService;
    }

    /**
     * Сохраняет картинку в Аватарницу для дальнейшей обработки, без привязки к фрилансеру.
     *
     * @return FileDescription содержит id загруженной картинки в Аватарнице
     */
    public WebResponse saveFile(Long freelancerId, MultipartFile file) {
        //В дальнейшем планируется вынести ограничения по размеру файла отдельно, см. DIRECT-86409
        if (file.getSize() > MAX_FILE_SIZE) {
            throw new FreelancerAvatarUploadException("Too large size");
        }
        byte[] avatarBytes;
        try {
            avatarBytes = file.getBytes();
        } catch (IOException e) {
            throw new FreelancerAvatarUploadException("Cannot process file", e);
        }
        Result<Long> saveAvatarResult = freelancerClientAvatarService.saveAvatar(freelancerId, avatarBytes);
        if (!saveAvatarResult.isSuccessful()) {
            return validationResultConversionService.buildValidationResponse(saveAvatarResult);
        }
        Long avatarId = saveAvatarResult.getResult();
        String url = freelancerClientAvatarService.getUrlSize180(clientAvatarIdFromParams(freelancerId, avatarId));
        FileDescription fileDescription = new FileDescription().setKey(avatarId.toString()).setUrl(url);
        return new FreelancerAvatarUploadResponse().withResult(fileDescription);
    }
}
