package com.r11.tools.service;

import com.r11.tools.model.Event;
import com.r11.tools.model.EventRequestDto;
import com.r11.tools.repository.EventRepository;
import com.r11.tools.utilis.BusinessKey;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Spring Service for {@link com.r11.tools.controller.EventController}. Contains logic required for quering
 * the database for {@link Event} objects
 * @author Rafał Żukowicz
 */
@Service
@AllArgsConstructor
public class EtrackServiceImpl implements EtrackService {

    private final EventRepository eventRepository;

    /**
     * Adds {@link BusinessKey} to {@link EventRequestDto}
     * in order to create query via{@link com.r11.tools.repository.EventRepositoryImpl}
     * @param eventsDto object containing required data for request
     * @return list of {@link Event}
     */
    @Override
    public List<Event> getEventsByDateTimeAndBusinessKeys(EventRequestDto eventsDto) {
        Map<BusinessKey, String> businessKeys = new HashMap<>();
        businessKeys.put(BusinessKey.CLIENT_UUID, eventsDto.getClientUUID().toString());
        if (eventsDto.getMockedResponseId() != null){
            businessKeys.put(BusinessKey.MESSAGE_ID, String.valueOf(eventsDto.getMockedResponseId()));
        }
        List<Event> events = eventRepository.findEvents(eventsDto.getLocalDateTimeFrom(), eventsDto.getLocalDateTimeTo(),
                businessKeys);
        Collections.sort(events);
        return events;
    }
}
