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

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import lombok.RequiredArgsConstructor;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;

import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.core.WebmasterException;
import ru.yandex.webmaster3.core.http.Action;
import ru.yandex.webmaster3.core.http.WriteAction;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.storage.importanturls.ImportantUrlsService;
import ru.yandex.webmaster3.storage.importanturls.data.ImportantUrl;
import ru.yandex.webmaster3.storage.importanturls.data.ImportantUrlRequest;
import ru.yandex.webmaster3.storage.importanturls.data.RecommendedUrl;

/**
 * @author avhaliullin
 */
@WriteAction
@Description("Добавить все рекомендованные страницы в отслеживание")
@Category("importanturls")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class AddAllRecommendedUrlsAction extends Action<AddAllRecommendedUrlsRequest, AddAllRecommendedUrlsResponse> {
    private final ImportantUrlsService importantUrlsService;

    @Override
    public AddAllRecommendedUrlsResponse process(AddAllRecommendedUrlsRequest request) throws WebmasterException {
        ImportantUrlsService.ImportantUrlsQuota importantUrlsQuota =
                importantUrlsService.getImportantUrlsQuota(request.getHostId());
        if (importantUrlsQuota.quotaIsEnd()) {
            return new AddAllRecommendedUrlsResponse(importantUrlsQuota.getQuotaTotal(),
                    importantUrlsQuota.getQuotaUsed(), importantUrlsQuota.getQuotaRemain(), Collections.emptyList());
        }

        List<ImportantUrlRequest> importantUrls = importantUrlsService.listImportantUrlRequests(request.getHostId());
        List<RecommendedUrl> recommendedUrls = importantUrlsService.listRecommendedUrls(request.getHostId(), importantUrls.stream()
                .map(ImportantUrlRequest::getRelativeUrl).collect(Collectors.toSet()));
        DateTime now = DateTime.now();
        List<ImportantUrlRequest> toAdd = recommendedUrls.stream()
                .filter(url -> !url.isImportantUrl())
                .map(url -> new ImportantUrlRequest(request.getHostId(), url.getRelativeUrl(), now))
                .limit(importantUrlsQuota.getQuotaRemain())
                .collect(Collectors.toList());
        importantUrlsService.addImportantUrls(toAdd);
        int quotaUsed = importantUrlsQuota.getQuotaUsed() + toAdd.size();
        int quotaRemain = Math.max(0, importantUrlsQuota.getQuotaTotal() - quotaUsed);
        return new AddAllRecommendedUrlsResponse(importantUrlsQuota.getQuotaTotal(), quotaUsed, quotaRemain, toAdd.stream().map(ImportantUrl::createFromRequest).collect(Collectors.toList()));
    }
}
