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

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

import javax.annotation.Nullable;

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.video.VideoCreativesService;

public class RebuildVideoOperation extends SingleCreativeTypeIdsOperation<Addition, SingleCreativeTypeOperationRequest>
        implements SingleCreativeTypeOperation<SingleCreativeTypeOperationRequest> {

    private final VideoCreativesService videoCreativesService;

    public RebuildVideoOperation(VideoCreativesService videoCreativesService) {
        this.videoCreativesService = videoCreativesService;
    }

    @Override
    public List<OnCreativeOperationResult> process(List<Addition> creatives) {
        List<OnCreativeOperationResult> result = new ArrayList<>();
        for (Addition addition : creatives) {
            String errorMessage = rebuildAdditionVast(addition);

            OnCreativeOperationResult opResult = errorMessage == null
                    ? OnCreativeOperationResult.ok()
                    : OnCreativeOperationResult.error(errorMessage);

            result.add(opResult);
        }

        return result;
    }

    @Nullable
    private String rebuildAdditionVast(Addition addition) {
        Long creativeId = addition.getCreativeId();
        Long stockCreativeId = addition.getStockCreativeId();
        if (stockCreativeId != null && !creativeId.equals(stockCreativeId)) {
            return "Rebuild stock video addition VAST (id: " + stockCreativeId
                    + ") instead of rebuilding addition built on top of it";
        }

        try {
            videoCreativesService.patchAdditionVast(addition);
        } catch (Exception e) {
            getLogger().error("Rebuild creative creative to direct: ", e);
            return "Rebuild creative error: " + e.getMessage();
        }

        return null; // ok
    }

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