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

import java.util.List;

import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.regions.W3RegionsTreeService;
import ru.yandex.webmaster3.storage.searchquery.HostSearchQueryRegionInfo;
import ru.yandex.webmaster3.storage.searchquery.dao.MdbHostSearchQueryRegionsCHDao;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostAction;
import ru.yandex.webmaster3.viewer.regions.SearchQueryRegionsIndexService;

/**
 * @author avhaliullin
 */
@ReadAction
@Description("Ручка для отображения дерева регионов в разделах про статистику по запросам")
@Category("searchquery")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class SearchQueryRegionsAction extends AbstractUserVerifiedHostAction<SearchQueryRegionsRequest, SearchQueryRegionsResponse> {

    private final MdbHostSearchQueryRegionsCHDao mdbHostSearchQueryRegionsCHDao;
    private final SearchQueryRegionsIndexService searchQueryRegionsIndexService;
    private final W3RegionsTreeService w3regionsTreeService;

    @Override
    public SearchQueryRegionsResponse process(SearchQueryRegionsRequest request) {
        String filter = request.getFilter();
        if (filter != null) {
            filter = filter.trim().toLowerCase();
            if (StringUtils.isEmpty(filter)) {
                filter = null;
            }
        }
        RegionsTreeBuilder builder = new RegionsTreeBuilder(searchQueryRegionsIndexService, w3regionsTreeService, filter, request.getRegionId());
        List<HostSearchQueryRegionInfo> infos = mdbHostSearchQueryRegionsCHDao
                .getRegionsForHost(
                        request.getHostId(),
                        request.getFromDate() == null ? null : request.getFromDate().toLocalDate(),
                        request.getToDate() == null ? null : request.getToDate().toLocalDate()
                );
        for (HostSearchQueryRegionInfo info : infos) {
            builder.addRegion(info);
        }
        return new SearchQueryRegionsResponse(builder.build());
    }
}
