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

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

import ru.yandex.canvas.model.video.Addition;
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.VideoAdditionScreenshooterHelperService;
import ru.yandex.direct.screenshooter.client.model.ScreenShooterScreenshot;

public class ScreenshotVideoOperation
        extends SingleCreativeTypeIdsOperation<Addition, SingleCreativeTypeOperationRequest>
        implements SingleCreativeTypeOperation<SingleCreativeTypeOperationRequest> {
    private final VideoAdditionScreenshooterHelperService videoAdditionScreenshooterHelperService;

    public ScreenshotVideoOperation(VideoAdditionScreenshooterHelperService videoAdditionScreenshooterHelperService) {
        this.videoAdditionScreenshooterHelperService = videoAdditionScreenshooterHelperService;
    }

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

    @Override
    public List<OnCreativeOperationResult> process(List<Addition> additions) {
        List<OnCreativeOperationResult> result = new ArrayList<>();

        for (Addition addition : additions) {
            ScreenShooterScreenshot screenshot;
            try {
                screenshot = videoAdditionScreenshooterHelperService.getScreenshot(addition, null, null);
            } catch (Exception e) {
                getLogger().error("Error while reshooting video creative screenshot: ", e);
                result.add(OnCreativeOperationResult
                        .error("Exception happened while making screenshot: " + e.getMessage()));
                continue;
            }

            if (screenshot.getIsDone()) {
                result.add(OnCreativeOperationResult.ok());
            } else {
                result.add(OnCreativeOperationResult.error("Screenshot has not been done, additionId=" + addition.getId()));
            }
        }

        return result;
    }
}
