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

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Required;

import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.core.http.RequestQueryProperty;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.util.IdUtils;
import ru.yandex.webmaster3.storage.importanturls.ImportantUrlsService;
import ru.yandex.webmaster3.storage.importanturls.data.ImportantUrlRequest;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostAction;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostRequest;
import ru.yandex.webmaster3.viewer.http.importanturls.GetNonExistentImportantUrlsAction.Request;

/**
 * @author Oleg Bazdyrev
 */
@ReadAction
@Description("Проверка наличия урла среди добавленных важных")
@Category("importanturls")
public class GetNonExistentImportantUrlsAction extends AbstractUserVerifiedHostAction<Request, GetNonExistentImportantUrlsResponse> {

    private ImportantUrlsService importantUrlsService;

    @Override
    public GetNonExistentImportantUrlsResponse process(Request request) {
        // имеющиеся урлы
        WebmasterHostId hostId = request.getHostId();
        Set<String> existingUrls = importantUrlsService.listImportantUrlRequests(hostId)
                .stream()
                .map(ImportantUrlRequest::getRelativeUrl)
                .collect(Collectors.toSet());

        // соберем отсутствующие (предполагаем, что в запросе только относительные ссылки)
        List<String> nonExistent = new ArrayList<>();
        List<String> unmatchedHost = new ArrayList<>();
        for (String url : request.getUrls()) {
            try {
                String relativeUrl = IdUtils.toRelativeUrl(request.getHostId(), url, false);
                if (relativeUrl == null) {
                    unmatchedHost.add(url);
                    continue;
                } else if (existingUrls.contains(relativeUrl)) {
                    continue;
                }
            } catch (Exception ignored) {
            }
            nonExistent.add(url);
        }

        ImportantUrlsService.ImportantUrlsQuota quota =
                importantUrlsService.getImportantUrlsQuota(request.getHostId());

        return new GetNonExistentImportantUrlsResponse(quota.getQuotaTotal(), quota.getQuotaUsed(), quota.getQuotaRemain(),
                nonExistent, unmatchedHost);
    }

    @Required
    public void setImportantUrlsService(ImportantUrlsService importantUrlsService) {
        this.importantUrlsService = importantUrlsService;
    }

    public static final class Request extends AbstractUserVerifiedHostRequest {

        private List<String> urls;

        public List<String> getUrls() {
            return urls;
        }

        @RequestQueryProperty(required = true)
        @Description("Искомые урлы для проверки")
        public void setUrls(List<String> urls) {
            this.urls = urls;
        }
    }

}
