package com.sonymusic.dx.dxadvsearchservice.service;

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

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 com.sonymusic.dx.dxadvsearchservice.dto.LabelDTO;
import com.sonymusic.dx.dxadvsearchservice.repository.LabelRepository;
import com.sonymusic.dx.persistence.gras.Label;

@Service
public class LabelService {

    @Autowired
    LabelRepository labelRepository;

    public Map<String, Object> getListOfLabels(String name,int page, int size) {
        Pageable pageable = PageRequest.of(page-1,size, Sort.by("labelName"));
        if(name!=null && !name.trim().isEmpty()){
            Page<Label> label = labelRepository.findByLabelNameIgnoreCaseContaining(name,pageable);
            List<LabelDTO> labelDTO = label.stream()
                    .map(c-> new LabelDTO(c.getLabelKey(),c.getLabelName()))
                    .collect(Collectors.toList());
            return mapToLabelDTO(label,page,labelDTO);
        }
        Page<Label> label = labelRepository.findAll(pageable);
        List<LabelDTO> labelDTO = label.stream()
                .map(c-> new LabelDTO(c.getLabelKey(),c.getLabelName()))
                .collect(Collectors.toList());
        return mapToLabelDTO(label,page,labelDTO);
    }

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