package kr.co.jinwoosi.clfd.clfd.dgns.service;

import kr.co.jinwoosi.clfd.clfd.dgns.mapper.DgnsAskMapper;
import kr.co.jinwoosi.clfd.clfd.dgns.model.DgnsAns;
import kr.co.jinwoosi.clfd.clfd.dgns.model.DgnsAnsSearch;
import kr.co.jinwoosi.clfd.clfd.dgns.model.DgnsAsk;
import kr.co.jinwoosi.clfd.clfd.dgns.model.DgnsAskSearch;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class DgnsAskService {

    public static List<DgnsAsk> cashedDgnsAskList = null;

    @Autowired
    private DgnsAskMapper dgnsAskMapper;

    @Autowired
    private DgnsAnsService dgnsAnsService;

    public List<DgnsAsk> selectList(DgnsAskSearch dgnsAskSearch) {
        return dgnsAskMapper.selectList(dgnsAskSearch);
    }

    public DgnsAsk select(DgnsAskSearch dgnsAskSearch) {
        return dgnsAskMapper.select(dgnsAskSearch);
    }

    public List<DgnsAsk> selectListWithDgnsAns(DgnsAskSearch dgnsAskSearch) {
        List<DgnsAsk> dgnsAskList = selectList(dgnsAskSearch);
        List<DgnsAns> dgnsAnsList = dgnsAnsService.selectList(new DgnsAnsSearch());
        dgnsAskList.forEach(dgnsAsk ->
            dgnsAsk.setDgnsAnsList(
                    dgnsAnsList
                        .stream()
                        .filter(dgnsAns -> dgnsAsk.getDgnsAskId() == dgnsAns.getDgnsAskId())
                        .collect(Collectors.toList())
            )
        );
        return dgnsAskList;
    }

    public List<DgnsAsk> getCashedDgnsAskList(boolean refresh) {
        if (refresh || cashedDgnsAskList == null) {
            cashedDgnsAskList = selectListWithDgnsAns(new DgnsAskSearch());
        }
        return cashedDgnsAskList;
    }

}
