package ru.yandex.webmaster3.api.turbo.action.v31;

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

import lombok.RequiredArgsConstructor;
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.rest.AbstractApiAction;
import ru.yandex.webmaster3.core.WebmasterException;
import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.core.http.WebmasterErrorResponse;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.turbo.model.feed.TurboApiTaskWithResult;
import ru.yandex.webmaster3.storage.turbo.dao.api.TurboApiHostTasksYDao;

/**
 * Created by ifilippov5 on 29.05.18.
 */
@Category("turbo")
@Description("Возвращает список пушей за последний месяц")
@Component
@ActionPermission(Permission.TURBO)
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class GetTurboPushListV31Action extends AbstractApiAction<GetTurboPushListV31Request, GetTurboPushListV31Response> {

    private final TurboApiHostTasksYDao turboApiHostTasksYDao;

    @Override
    public GetTurboPushListV31Response process(GetTurboPushListV31Request request) {
        try {
            WebmasterHostId hostId = request.getHostId();
            GetTurboPushListV31Request.TaskTypeFilter mode = request.getTaskTypeFilter();
            Boolean activeFilter = mode == null ? null : mode.getValue();
            int count = (int) turboApiHostTasksYDao.getTasksCount(hostId, activeFilter, null);
            List<UUID> pushIds = turboApiHostTasksYDao.getTasks(hostId, activeFilter, null, request.getOffset(), request.getLimit())
                    .stream().map(TurboApiTaskWithResult::getTaskId).collect(Collectors.toList());
            return new GetTurboPushListV31Response.NormalResponse(
                    pushIds.stream().map(GetTurboPushListV31Response.ListItem::new).collect(Collectors.toList()),
                    count
            );

        } catch (Exception e) {
            throw new WebmasterException("Failed to list turbo tasks", new WebmasterErrorResponse.InternalUnknownErrorResponse(getClass(), null), e);
        }
    }

}
