package ru.yandex.canvas.service.multitype.singletype;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

import ru.yandex.canvas.exceptions.InternalServerError;
import ru.yandex.canvas.model.html5.Creative;
import ru.yandex.canvas.service.RTBHostExportService;
import ru.yandex.canvas.service.html5.Html5SourcesService;
import ru.yandex.canvas.service.multitype.CreativeType;
import ru.yandex.canvas.service.multitype.OnCreativeOperationResult;
import ru.yandex.canvas.service.multitype.SingleCreativeTypeOperation;
import ru.yandex.canvas.service.multitype.singletype.request.SingleCreativeTypeOperationRequest;
import ru.yandex.canvas.service.rtbhost.RtbHostUploadHelper;

public class SendToRtbHostHtml5Operation extends SendToRtbHostBaseOperation<Creative>
        implements SingleCreativeTypeOperation<SingleCreativeTypeOperationRequest> {
    private final Html5SourcesService sourcesService;

    public SendToRtbHostHtml5Operation(
            RtbHostUploadHelper<Creative> rtbHostUploadHelper,
            RTBHostExportService rtbHostExportService, Html5SourcesService sourcesService) {
        super(rtbHostUploadHelper, rtbHostExportService);
        this.sourcesService = sourcesService;
    }

    @Override
    public List<OnCreativeOperationResult> process(List<Creative> creatives) {
        try {
            sourcesService.downloadZipContent(creatives.stream().map(c -> c.getSource()).collect(Collectors.toList()));
        } catch (IOException | InterruptedException e) {
            throw new InternalServerError("export failed", e);
        }

        return super.process(creatives);
    }

    @Override
    public CreativeType worksOn() {
        return CreativeType.HTML5;
    }
}
