package ru.yandex.webmaster3.worker.http.periodic;

import java.util.Collections;
import java.util.List;

import org.springframework.beans.factory.annotation.Required;

import ru.yandex.webmaster3.core.WebmasterException;
import ru.yandex.webmaster3.core.http.Action;
import ru.yandex.webmaster3.core.util.PageUtils;
import ru.yandex.webmaster3.storage.logging.TaskLogEntry;
import ru.yandex.webmaster3.storage.logging.TasksLoggingService;

/**
 * @author tsyplyaev
 */
public class GetPeriodicTasksLogAction extends Action<GetPeriodicTasksLogRequest, GetPeriodicTasksLogResponse> {
    private TasksLoggingService periodicTasksLoggingService;

    @Override
    public GetPeriodicTasksLogResponse process(GetPeriodicTasksLogRequest request) throws WebmasterException {
        long count = periodicTasksLoggingService.countEntries(
                request.getFromDate(),
                request.getToDate(),
                request.getEventType(),
                request.getTaskType(),
                request.getHostName(),
                request.getRunId(),
                request.getHideZero()
        );

        PageUtils.LongPager page = PageUtils.getPage(request.getPage(), request.getPageSize(), count);
        List<String> taskTypes = periodicTasksLoggingService.distinctTaskTypes();
        List<String> hostNames = periodicTasksLoggingService.distinctHostnames();

        if (page.isEmpty()) {
            return new GetPeriodicTasksLogResponse(count, Collections.emptyList(), taskTypes, hostNames);
        } else {
            List<TaskLogEntry> entries = periodicTasksLoggingService.listEntries(
                    request.getFromDate(),
                    request.getToDate(),
                    request.getEventType(),
                    request.getTaskType(),
                    request.getHostName(),
                    request.getRunId(),
                    request.getHideZero(),
                    (int) page.toRangeStart(),
                    page.getPageSize(),
                    request.getOrderBy(),
                    request.getOrderDirection());

            return new GetPeriodicTasksLogResponse(count, entries, taskTypes, hostNames);
        }
    }

    @Required
    public void setPeriodicTasksLoggingService(TasksLoggingService periodicTasksLoggingService) {
        this.periodicTasksLoggingService = periodicTasksLoggingService;
    }
}
