package ru.yandex.webmaster3.viewer.http.url.checker2;

import org.springframework.beans.factory.annotation.Required;
import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.storage.url.checker2.UrlCheckRequestService;
import ru.yandex.webmaster3.storage.url.common.data.UrlCheckRequestData;
import ru.yandex.webmaster3.storage.url.checker2.data.UrlCheckResultData;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostAction;
import ru.yandex.webmaster3.viewer.http.url.checker2.data.UrlCheckReport;

import java.util.Optional;

/**
 * Created by leonidrom on 01/03/2017.
 */
@Description("Результат заявки на проверку урла")
@ReadAction
@Category("checkurl")
public class GetUrlCheckReportAction extends AbstractUserVerifiedHostAction<GetUrlCheckReportRequest, GetUrlCheckReportResponse> {
    private UrlCheckRequestService urlCheckRequestService;

    @Override
    public GetUrlCheckReportResponse process(GetUrlCheckReportRequest request) {
        Optional<UrlCheckRequestData> checkRequestOpt = urlCheckRequestService.getRequest(
                request.getHostId(), request.getRequestId());
        if (!checkRequestOpt.isPresent()) {
            return new GetUrlCheckReportResponse.RequestNotFoundErrorResponse();
        }

        Optional<UrlCheckResultData> resultOpt = urlCheckRequestService.getResult(
                request.getHostId(), request.getRequestId());
        if (!resultOpt.isPresent()) {
            return new GetUrlCheckReportResponse.ReportNotReadyErrorResponse();
        }

        UrlCheckResultData checkResult = resultOpt.get();
        UrlCheckReport report = UrlCheckReport.from(checkRequestOpt.get().getUrl(), checkResult.getInfo());

        return new GetUrlCheckReportResponse.NormalResponse(report);
    }

    @Required
    public void setUrlCheckRequestService(UrlCheckRequestService urlCheckRequestService) {
        this.urlCheckRequestService = urlCheckRequestService;
    }
}


