package com.sonymusic.dx.dxadvsearchservice.service;

import com.sonymusic.dx.dxadvsearchservice.dto.ParticipantDTO;
import com.sonymusic.dx.dxadvsearchservice.repository.ParticipantRepository;
import com.sonymusic.dx.persistence.gras.Participant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

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

@Service
public class ParticipantListService {

    @Autowired
    ParticipantRepository participantRepository;


    public Map<String, Object> getParticipantList(String name, int page, int size) {
        Pageable pageable = PageRequest.of(page-1,size, Sort.by("fullName"));
        if(name!=null && !name.trim().isEmpty()){
            Page<Participant> participants = participantRepository.findByFullNameIgnoreCaseContaining(name,pageable);
            List<ParticipantDTO> participantDTO = participants.stream()
                    .map(c-> new ParticipantDTO(c.getParticipantNo(),c.getFullName(),c.isPreferredParticipant()))
                    .collect(Collectors.toList());
            return mapToParticipantDTO(participants,page,participantDTO);
        }
        Page<Participant> participants = participantRepository.findAll(pageable);
        List<ParticipantDTO> participantDTO = participants.stream()
                .map(c-> new ParticipantDTO(c.getParticipantNo(),c.getFullName(),c.isPreferredParticipant()))
                .collect(Collectors.toList());
        return mapToParticipantDTO(participants,page,participantDTO);

    }

    public <T,D> Map<String,Object> mapToParticipantDTO(Page<T> participantList, int page, List<ParticipantDTO> list){
        Map<String,Object> result= new HashMap<>();
        result.put("data",list);
        result.put("totalCount",participantList.getTotalElements());
        result.put("page", page);
        result.put("totalPage",participantList.getTotalPages());
        return result;
    }
}
