package ru.yandex.webmaster3.viewer.http.searchquery.regions;

import java.util.Collections;
import java.util.List;
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.W3RegionInfo;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.core.regions.RegionUtils;
import ru.yandex.webmaster3.core.regions.W3RegionsTreeService;
import ru.yandex.webmaster3.viewer.http.BaseWebmaster3Action;

/**
 * @author avhaliullin
 */
@ReadAction
@Description("Получить родителей для регионов")
@Category("searchquery")
public class SearchQueryRegionParentsAction extends BaseWebmaster3Action<SearchQueryRegionParentsRequest, SearchQueryRegionParentsResponse> {
    private W3RegionsTreeService w3regionsTreeService;

    @Override
    public SearchQueryRegionParentsResponse process(SearchQueryRegionParentsRequest request) {
        List<SearchQueryRegionParentsResponse.RegionWithParents> result = request.getRegionIds().stream()
                .map(regionId -> {
                    List<W3RegionInfo> parents = w3regionsTreeService.getVisibleParentsChain(regionId, RegionUtils.VISIBLE_OR_WHOLE_WORLD_PREDICATE);
                    Collections.reverse(parents);
                    return new SearchQueryRegionParentsResponse.RegionWithParents(regionId,
                            parents.stream()
                                    .map(r -> new SearchQueryRegionParentsResponse.RegionView(r.getId()))
                                    .collect(Collectors.toList()));
                })
                .collect(Collectors.toList());
        return new SearchQueryRegionParentsResponse(result);
    }

    @Required
    public void setW3regionsTreeService(W3RegionsTreeService w3regionsTreeService) {
        this.w3regionsTreeService = w3regionsTreeService;
    }
}
