package ru.yandex.webmaster3.storage.searchurl.download;

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

import lombok.RequiredArgsConstructor;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.core.sitestructure.StructureNodeFilter;
import ru.yandex.webmaster3.storage.searchurl.SearchUrlFilter;
import ru.yandex.webmaster3.storage.searchurl.SearchUrlSamplesService;
import ru.yandex.webmaster3.storage.searchurl.samples.dao.SearchUrlConditions;
import ru.yandex.webmaster3.storage.searchurl.samples.data.SearchUrlSample;
import ru.yandex.webmaster3.storage.searchurl.samples.data.UrlStatusInfo;
import ru.yandex.webmaster3.storage.util.StructureFilterService;
import ru.yandex.webmaster3.storage.util.clickhouse2.condition.Condition;

/**
 * Created by ifilippov5 on 11.02.17.
 */
@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class DownloadSearchUrlsService {

    private final SearchUrlSamplesService searchUrlSamplesService;
    private final StructureFilterService structureFilterService;
    private final SearchUrlConditions searchUrlConditions;

    public List<SearchUrlCsvRow> getSamples(WebmasterHostId hostId, List<SearchUrlFilter> parameterFilters, Long nodeId) {
        List<SearchUrlSample> samples = getInternalSamples(hostId, parameterFilters, nodeId);

        return samples.stream()
                .map(sample -> new SearchUrlCsvRow(
                        sample.getUrl(),
                        Optional.of(sample).map(SearchUrlSample::getLastAccess).map(date -> date.toString(DateTimeFormat.forPattern("dd.MM.yyyy"))).orElse(""),
                        Optional.ofNullable(sample.getTitle()).orElse(""),
                        Optional.of(sample).map(SearchUrlSample::getStatusInfo).map(UrlStatusInfo::isFromSitemap).map(SearchurlReportUtil::toStringYesNo).orElse("")

                ))
                .collect(Collectors.toList());
    }

    private List<SearchUrlSample> getInternalSamples(WebmasterHostId hostId, List<SearchUrlFilter> parameterFilters, Long nodeId) {
        List<SearchUrlSample> samples = Collections.emptyList();
        Condition condition = searchUrlConditions.makeCondition(hostId, false, parameterFilters);
        Condition freshCondition = searchUrlConditions.makeCondition(hostId, true, parameterFilters);
        if (nodeId != null) {
            StructureNodeFilter nodeFilter = structureFilterService.getNodeFilter(hostId, nodeId);
            if (nodeFilter == null) {
                //Такой ноды нет, так что "отфильтровали всё"
                return samples;
            }
            SearchUrlConditions.PathLikeConditionBuilder condBuilder = SearchUrlConditions.pathLikeConditionBuilder();
            for (StructureNodeFilter.Part part : nodeFilter.getFilterParts()) {
                if (part instanceof StructureNodeFilter.StringPart) {
                    condBuilder.append(((StructureNodeFilter.StringPart) part).getValue());
                } else {
                    condBuilder.appendWildcard();
                }
            }
            condition = condition.andThen(condBuilder.build());
        }
        long samplesCount = searchUrlSamplesService.getSearchUrlSamplesCount(hostId, condition, freshCondition);

        if (samplesCount == 0) {
            return samples;
        }
        samples = searchUrlSamplesService.getSearchUrlSamples(hostId, condition, freshCondition, 0, samplesCount);

        return samples;
    }
}
