package ru.yandex.webmaster3.worker.url.checker3.fetchers;

import NUrlChecker.Response;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.joda.time.DateTime;
import org.springframework.stereotype.Component;
import ru.yandex.webmaster3.core.WebmasterException;
import ru.yandex.webmaster3.core.http.WebmasterErrorResponse;
import ru.yandex.webmaster3.core.url.checker3.UrlCheckRequestParams;
import ru.yandex.webmaster3.core.util.GzipUtils;
import ru.yandex.webmaster3.core.zora.ZoraConversionUtil;
import ru.yandex.webmaster3.storage.url.checker3.data.UrlCheckDataBlockType;
import ru.yandex.webmaster3.storage.url.checker3.data.blocks.ServerResponseData;

import java.util.Arrays;

/**
 * @author leonidrom
 */
@Slf4j
@Component
public class ServerResponseRenderOffDataFetcher extends AbstractServerResponseDataFetcher {
    @Override
    public ServerResponseData doFetchBlock(DateTime searchBaseDate, UrlCheckRequestParams requestParams) throws Exception {
        return null;
    }

    @Override
    public ServerResponseData doFetchBlock(Response.TUrlCheckResponse response) throws Exception {
        var fetchResult = response.hasRotorlessFetchResult()? response.getRotorlessFetchResult() : null;
        if (fetchResult == null) {
            throw new WebmasterException("Empty zora fetch result",
                    new WebmasterErrorResponse.InternalUnknownErrorResponse(GzipUtils.class, "Empty zora fetch result"));
        }

        var zoraUrlFetchResponse = ZoraConversionUtil.toUrlFetchResponse(fetchResult);
        var httpResponsePart = processZoraUrlFetchResponse(zoraUrlFetchResponse);
        var resources = processResources(fetchResult);
        log.info("Resources: {}", Arrays.toString(resources.toArray()));

        return new ServerResponseData(httpResponsePart, resources);
    }

    @Override
    public Class<ServerResponseData> getDataBlockClass() {
        return ServerResponseData.class;
    }

    @Override
    public @NotNull UrlCheckDataBlockType getBlockType() {
        return UrlCheckDataBlockType.ROBOT_SERVER_RESPONSE_RENDER_OFF;
    }
}
