package com.r11.tools.service;

import com.r11.tools.controller.RequestHistoryController;
import com.r11.tools.mappers.RequestHistoryMapper;
import com.r11.tools.model.HistoryRequestModel;
import com.r11.tools.model.RequestHistory;
import com.r11.tools.model.RequestHistoryDTO;
import com.r11.tools.repository.RequestHistoryRepository;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

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

/**
 * Spring Service for {@link RequestHistoryController}. Contains logic required for quering
 * the database for {@link RequestHistory} objects
 * @author Rafał Żukowicz
 * @author Mikołaj Widła
 */
@Service
@AllArgsConstructor
public class RequestHistoryServiceImpl implements RequestHistoryService {

    private final RequestHistoryRepository repository;
    private final RequestHistoryMapper requestMapper;

    /**
     * in order to create query via{@link com.r11.tools.repository.RequestHistoryRepository}
     * @param historyRequestModel object containing required data for request
     * @return list of {@link RequestHistory}
     */
    @Override
    public List<RequestHistory> getHistoryRecordsBetweenDatesAndByUUIDAndMessageId(HistoryRequestModel historyRequestModel) {
        List<RequestHistory> history = repository.findAllByClientUUIDAndMessageID(
                historyRequestModel.getClientUUID().toString(),
                historyRequestModel.getMockedResponseId()
                );
        Collections.sort(history);

        return history.stream()
                .filter( historyRecord -> historyRecord
                        .getDateTimeStamp()
                        .isAfter(historyRequestModel.getLocalDateTimeFrom())
                ).filter(
                        historyRecord-> historyRecord
                                .getDateTimeStamp()
                                .isBefore(historyRequestModel.getLocalDateTimeTo())
                )
                .collect(Collectors.toList());
    }

    @Override
    public void saveRequest(RequestHistoryDTO requestDTO) {
        repository.save(requestMapper.requestHistoryDTOToRequestHistory(requestDTO));
    }
}
