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

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

import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.api.turbo.action.GetTurboPushListRequest.TaskTypeFilter;
import ru.yandex.webmaster3.api.turbo.action.GetTurboPushListResponse.ListItem;
import ru.yandex.webmaster3.api.turbo.data.TurboPushProcessStatus;
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.TurboCrawlState;
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 GetTurboPushListAction extends AbstractApiAction<GetTurboPushListRequest, GetTurboPushListResponse> {
    private static final Logger log = LoggerFactory.getLogger(GetTurboPushListAction.class);

    private final TurboApiHostTasksYDao turboApiHostTasksYDao;

    @Override
    public GetTurboPushListResponse process(GetTurboPushListRequest request) {
        try {
            WebmasterHostId hostId = request.getHostId();
            TaskTypeFilter taskType = request.getTaskTypeFilter();
            TurboPushProcessStatus loadStatus = request.getLoadStatusFilter();
            Boolean activeFilter = taskType == null ? null : taskType.getValue();
            TurboCrawlState statusFilter = loadStatus == null ? null : loadStatus.getState();
            int totalFilteredCount = (int) turboApiHostTasksYDao.getTasksCount(hostId, activeFilter, statusFilter);
            List<ListItem> result = turboApiHostTasksYDao.getTasks(hostId, activeFilter, statusFilter, request.getOffset(), request.getLimit())
                    .stream().map(ListItem::new).collect(Collectors.toList());
            return new GetTurboPushListResponse.NormalResponse(result, totalFilteredCount);
        } catch (Exception e) {
            throw new WebmasterException("Failed to list turbo tasks", new WebmasterErrorResponse.InternalUnknownErrorResponse(getClass(), null), e);
        }
    }

}
