package com.arms.api.admin.indexstatus.service;

import com.arms.api.admin.indexstatus.model.vo.IndexStatusesWithJobIdVO;
import com.arms.api.admin.indexstatus.model.entity.IndexStatusEntity;
import com.arms.egovframework.javaservice.esframework.model.vo.DocumentResultWrapper;
import com.arms.egovframework.javaservice.esframework.repository.common.EsCommonRepositoryWrapper;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

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

@Service
@AllArgsConstructor
public class IndexStatusServiceImpl implements IndexStatusService {

    private final EsCommonRepositoryWrapper<IndexStatusEntity> esCommonRepositoryWrapper;

    @Override
    public List<IndexStatusesWithJobIdVO> indexJobHistories(){

        DocumentResultWrapper<IndexStatusEntity> findAllHits = esCommonRepositoryWrapper.findAllHits();

        Map<String, List<IndexStatusEntity>> indexStatusEntitiesGroupByJobId
            = findAllHits.toDocs().stream()
                .collect(Collectors.groupingBy(IndexStatusEntity::getJobId));

        return indexStatusEntitiesGroupByJobId.entrySet().stream()
                .map(IndexStatusesWithJobIdVO::from)
                .sorted((a, b) -> {
                    if(b.getJobStartTime()!=null&&a.getJobStartTime()!=null){
                        return b.getJobStartTime().compareTo(a.getJobStartTime());
                    }else if(b.getJobEndTime()!=null&&a.getJobEndTime()!=null) {
                        return b.getJobEndTime().compareTo(a.getJobEndTime());
                    }
                    return -1;
                })
                .collect(Collectors.toList());

    }

}
