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

import NUrlChecker.Response;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import ru.yandex.webmaster3.core.WebmasterException;
import ru.yandex.webmaster3.core.http.WebmasterErrorResponse;
import ru.yandex.webmaster3.core.mobile.data.ScreenshotResolution;
import ru.yandex.webmaster3.core.url.checker3.UrlCheckRequestParams;
import ru.yandex.webmaster3.storage.mobile.data.MobileAuditResult;
import ru.yandex.webmaster3.storage.mobile.data.MobileAuditResultType;
import ru.yandex.webmaster3.storage.url.checker3.data.blocks.MobileAuditResultData;
import ru.yandex.webmaster3.storage.url.checker3.data.UrlCheckDataBlockType;
import ru.yandex.webmaster3.worker.mobile.MobileAuditService;
import ru.yandex.webmaster3.worker.url.checker3.AbstractUrlCheckDataBlockFetcher;

import java.net.URL;

/**
 * @author leonidrom
 */
@Component
@Slf4j
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class MobileAuditResultDataFetcher extends AbstractUrlCheckDataBlockFetcher<MobileAuditResultData> {
    private final MobileAuditService mobileAuditService;

    @Override
    public MobileAuditResultData doFetchBlock(DateTime searchBaseDate, UrlCheckRequestParams requestParams) throws Exception {
        MobileAuditResult auditResult = mobileAuditService.checkUrl(
                new URL(requestParams.getUrl()),
                new ScreenshotResolution(requestParams.getScreenshotWidth(), requestParams.getScreenshotHeight()));
        if (auditResult.getType() == MobileAuditResultType.INTERNAL_ERROR) {
            throw new WebmasterException("Internal error", new WebmasterErrorResponse.InternalUnknownErrorResponse(getClass(),
                    "Mobile audit internal error"));
        }

        return new MobileAuditResultData(auditResult);
    }

    @Override
    public MobileAuditResultData doFetchBlock(Response.TUrlCheckResponse response) throws Exception {
        return null;
    }

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

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