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

import java.util.ArrayList;
import java.util.List;

import ru.yandex.canvas.model.CreativeDocument;
import ru.yandex.canvas.service.multitype.CreativeType;
import ru.yandex.canvas.service.multitype.OnCreativeOperationResult;
import ru.yandex.canvas.service.multitype.SingleCreativeTypeIdsOperation;
import ru.yandex.canvas.service.multitype.SingleCreativeTypeOperation;
import ru.yandex.canvas.service.multitype.singletype.request.SingleCreativeTypeOperationRequest;
import ru.yandex.canvas.service.screenshooters.CreativesScreenshooterHelperService;
import ru.yandex.direct.screenshooter.client.model.ScreenShooterScreenshot;

public class ScreenshotAdBuilderOperation
        extends SingleCreativeTypeIdsOperation<CreativeDocument, SingleCreativeTypeOperationRequest>
        implements SingleCreativeTypeOperation<SingleCreativeTypeOperationRequest> {
    private final CreativesScreenshooterHelperService creativesScreenshooterHelperService;

    public ScreenshotAdBuilderOperation(CreativesScreenshooterHelperService creativesScreenshooterHelperService) {
        this.creativesScreenshooterHelperService = creativesScreenshooterHelperService;
    }

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

    @Override
    public List<OnCreativeOperationResult> process(List<CreativeDocument> creatives) {
        List<OnCreativeOperationResult> result = new ArrayList<>();
        for (CreativeDocument creative : creatives) {
            ScreenShooterScreenshot updateResult;
            try {
                updateResult = creativesScreenshooterHelperService.getScreenshot(creative,
                        null, creative.getClientId());
            } catch (RuntimeException e) {
                getLogger().error("Error while reshooting AdBuilder creative screenshot: ", e);
                result.add(OnCreativeOperationResult.error("Exception happened while making screenshot: " + e.getMessage()));
                continue;
            }

            if (updateResult.getIsDone()) {
                result.add(OnCreativeOperationResult.ok());
            } else {
                result.add(OnCreativeOperationResult.error("Taking screenshot's been failed, creativeId=" + creative.getId()));
            }
        }
        return result;
    }
}
