package ru.yandex.webmaster3.api.importanturls.action;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import ru.yandex.webmaster3.api.http.auth.Permission;
import ru.yandex.webmaster3.api.http.rest.AbstractApiAction;
import ru.yandex.webmaster3.api.importanturls.data.ApiImportantUrl;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.storage.importanturls.ImportantUrlsService;
import ru.yandex.webmaster3.storage.importanturls.data.ImportantUrl;

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

/**
 * @author leonidrom
 */
@Component
@Category("importanturls")
public class ListImportantUrlsAction extends AbstractApiAction<ListImportantUrlsRequest, ListImportantUrlsResponse> {
    @Autowired
    private ImportantUrlsService importantUrlsService;

    public ListImportantUrlsAction() {
        super(Permission.COMMON);
    }

    @Override
    public ListImportantUrlsResponse process(ListImportantUrlsRequest request) {
        List<ImportantUrl> importantUrls = importantUrlsService.listImportantUrls(request.getHostId());
        // сортируем по дате последнего обновления
        importantUrls.sort(ImportantUrl.BY_UPDATE_TIME_AND_RELATIVE_URL.reversed());

        List<ApiImportantUrl> statuses = importantUrls.stream()
                .map(ApiImportantUrl::fromCoreImportantUrl)
                .collect(Collectors.toList());

        return new ListImportantUrlsResponse(statuses);
    }
}
