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

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;

import org.joda.time.DateTime;
import org.joda.time.Instant;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Component;

import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.api.http.auth.Permission;
import ru.yandex.webmaster3.api.http.common.data.ApiHistoryPoint;
import ru.yandex.webmaster3.api.http.rest.AbstractApiAction;
import ru.yandex.webmaster3.core.http.UserContext;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.sitestructure.NewSiteStructure;
import ru.yandex.webmaster3.core.util.TimeUtils;
import ru.yandex.webmaster3.storage.searchurl.history.SearchUrlHistoryService;
import ru.yandex.webmaster3.storage.searchurl.history.data.SearchUrlHistoryIndicator;
import ru.yandex.webmaster3.storage.searchurl.history.data.SearchUrlHistoryPoint;

/**
 * @author avhaliullin
 */
@Description("История количества страниц сайта в поиске")
@Category("searchurls")
@Component
public class SearchUrlHistoryAction extends AbstractApiAction<SearchUrlHistoryRequest, SearchUrlHistoryResponse> {
    private SearchUrlHistoryService searchUrlHistoryService;

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

    @Override
    public SearchUrlHistoryResponse process(SearchUrlHistoryRequest request) {
        DateTime dateFrom = request.getDateFrom();
        DateTime dateTo = request.getDateTo();
        UserContext.setUserId(request.getUserId());

        // получим историю для ROOT_NODE_ID
        NavigableMap<Instant, SearchUrlHistoryPoint> rawHistory = searchUrlHistoryService.getSearchHistory(
                request.getHostId(),
                Collections.singleton(NewSiteStructure.ROOT_NODE_ID),
                Collections.singleton(SearchUrlHistoryIndicator.COUNT),
                dateFrom == null? null : dateFrom.toInstant(),
                dateTo == null? null : dateTo.toInstant()
        );

        // и приведем ее к нужному виду
        List<ApiHistoryPoint<Long>> historyPoints = new ArrayList<>();
        for (Map.Entry<Instant, SearchUrlHistoryPoint> entry : rawHistory.entrySet()) {
            Map<Long, Map<SearchUrlHistoryIndicator, Long>> node2Values = entry.getValue().getNode2Values();

            // нас интересует история только ROOT_NODE_ID
            Map<SearchUrlHistoryIndicator, Long> indicatorsMap = node2Values.get(NewSiteStructure.ROOT_NODE_ID);
            if (indicatorsMap == null) {
                continue;
            }

            // получим значение индикатора
            Long countValue = indicatorsMap.get(SearchUrlHistoryIndicator.COUNT);
            if (countValue != null) {
                // и добавим его к списку
                DateTime historyDate = entry.getKey().toDateTime(TimeUtils.EUROPE_MOSCOW_ZONE);
                historyPoints.add(new ApiHistoryPoint<>(historyDate, countValue));
            }
        }

        return new SearchUrlHistoryResponse(historyPoints);
    }

    @Required
    public void setSearchUrlHistoryService(SearchUrlHistoryService searchUrlHistoryService) {
        this.searchUrlHistoryService = searchUrlHistoryService;
    }
}
