package ru.yandex.webmaster3.viewer.http.common;

import lombok.RequiredArgsConstructor;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.core.feeds.feed.NativeFeedSccStatus;
import ru.yandex.webmaster3.core.http.ActionResponse;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.util.WwwUtil;
import ru.yandex.webmaster3.storage.feeds.FeedsNative2YDao;
import ru.yandex.webmaster3.storage.turbo.dao.scc.TurboSccService;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostAction;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostRequest;

import static ru.yandex.webmaster3.storage.turbo.dao.scc.TurboSccService.SCC_DEADLINE;

/**
 * ishalaru
 * 23.09.2020
 **/
@ReadAction
@Category("common")
@Slf4j
@Component("/common/getCachedImportantData")
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class GetCachedImportantDataAction extends AbstractUserVerifiedHostAction<GetCachedImportantDataAction.Request, GetCachedImportantDataAction.Response> {

    private final TurboSccService turboSccService;
    private final FeedsNative2YDao feedsNative2YDao;


    @Override
    public Response process(Request request) {
        WebmasterHostId hostId = request.getHostId();
        String domain = WwwUtil.cutWWWAndM(hostId);
        boolean hasFeedsWithFailedScc = feedsNative2YDao.list(domain)
                .stream()
                .anyMatch(x -> x.getStatusScc() == NativeFeedSccStatus.FAILED || x.getStatusScc() == NativeFeedSccStatus.DISABLED_BY_PINGER);
        return new Response.NormalResponse(turboSccService.getStatus(request.getHostId()), hasFeedsWithFailedScc);
    }


    public static class Request extends AbstractUserVerifiedHostRequest {

    }

    public static abstract class Response implements ActionResponse {

        @Value
        public static class NormalResponse extends Response implements ActionResponse.NormalResponse {
            TurboSccService.FrontModerationStatus status;
            boolean hasFeedsWithFailedScc;

            public DateTime getSccDeadline() {
                return SCC_DEADLINE;
            }
        }
    }
}
