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

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

import lombok.RequiredArgsConstructor;
import org.joda.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.api.http.auth.ActionPermission;
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.link.DatePoint;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.storage.iks.IksService;

/**
 * @author avhaliullin
 */
@Description("Получить историю значений ИКС для сайта")
@Category("sqi")
@Component
@ActionPermission(Permission.COMMON)
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class SqiHistoryAction extends AbstractApiAction<SqiHistoryRequest, SqiHistoryResponse> {

    private static final LocalDate DEFAULT_DATE_FROM = LocalDate.parse("2018-08-31");
    private final IksService iksService;

    @Override
    public SqiHistoryResponse process(SqiHistoryRequest request) {
        LocalDate dateFrom = request.getDateFrom() == null ? DEFAULT_DATE_FROM : request.getDateFrom().toLocalDate();
        LocalDate dateTo = request.getDateTo() == null ? LocalDate.now() : request.getDateTo().toLocalDate();

        List<DatePoint> datePoints = iksService.getIksHistory(iksService.getMascotOwner(request.getHostId()), dateFrom.minusMonths(2), dateTo);

        List<ApiHistoryPoint<Long>> historyPoints = datePoints.stream().map(ApiHistoryPoint::fromDatePoint).collect(Collectors.<ApiHistoryPoint<Long>>toList());

        return new SqiHistoryResponse(historyPoints);
    }

}
