package ru.yandex.webmaster3.admin.action.events;

import java.util.List;

import lombok.Setter;

import ru.yandex.webmaster3.admin.security.action.AdminAction;
import ru.yandex.webmaster3.core.WebmasterException;
import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.core.events2.HostEvent;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.core.http.WebmasterErrorResponse;
import ru.yandex.webmaster3.core.util.IdUtils;
import ru.yandex.webmaster3.core.util.PageUtils;
import ru.yandex.webmaster3.storage.admin.security.AccessObjectEnum;
import ru.yandex.webmaster3.storage.events2.HostEventsCHDao;
import ru.yandex.webmaster3.storage.events2.HostEventsFilter;
import ru.yandex.webmaster3.storage.util.clickhouse2.ClickhouseException;

/**
 * @author avhaliullin
 */
@ReadAction
public class ListHostEventsAction extends AdminAction<ListHostEventsRequest, ListHostEventsResponse> {
    @Setter
    private HostEventsCHDao mdbHostEventsCHDao;

    public ListHostEventsAction() {
        super(AccessObjectEnum.HOST_EVENTS);
    }

    @Override
    public ListHostEventsResponse process(ListHostEventsRequest request) throws WebmasterException {
        WebmasterHostId hostId = request.getHostNameFilter() == null ? null :
                IdUtils.urlToHostId(request.getHostNameFilter());
        HostEventsFilter filter = new HostEventsFilter(
                hostId,
                request.getRequestIdFilter(),
                request.getTaskIdFilter(),
                request.getUserIdFilter(),
                request.getAdminUserIdFilter(),
                request.getDateFromFilter() == null ? null : request.getDateFromFilter().toInstant(),
                request.getDateToFilter() == null ? null : request.getDateToFilter().toInstant(),
                request.getEventTypesFilter()
        );

        try {
            long totalEvents = mdbHostEventsCHDao.countEvents(filter);
            List<HostEvent> events = mdbHostEventsCHDao.listEvents(filter, PageUtils.getPage(request.getP(),
                    request.getPSize()));
            return new ListHostEventsResponse(totalEvents, events);
        } catch (ClickhouseException e) {
            throw new WebmasterException("Failed to get events info",
                    new WebmasterErrorResponse.ClickhouseErrorResponse(getClass(), null), e);
        }
    }
}
