package cokr.xit.fims.crdn.service.bean;

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

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import cokr.xit.base.file.FileInfo;
import cokr.xit.base.file.service.bean.FileBean;
import cokr.xit.fims.crdn.Crdn;
import cokr.xit.fims.crdn.service.CrdnService;
import cokr.xit.fims.crdn.service.ImportService;
import cokr.xit.foundation.component.AbstractServiceBean;
import cokr.xit.interfaces.smg.Petition;
import cokr.xit.interfaces.smg.service.bean.SmgReceiverBean;

/**외부 연계 파일에서 단속자료를 추출하여 등록하는 서비스의 구현체
 * @author mjkhan
 */
@Service("importService")
public class ImportServiceBean extends AbstractServiceBean implements ImportService {
	@Resource(name = "smgReceiverBean")
	private SmgReceiverBean smgBean;
	@Resource(name = "importBean")
	private ImportBean importBean;
	@Resource(name = "fileBean")
	private FileBean fileBean;
	@Resource(name = "crdnService")
	private CrdnService crdnService;
	@Resource(name = "crdnBean")
	private CrdnBean crdnBean;
	@Override
	public int createCrdns(List<String> interfaceSequences) {
		List<Petition> petitions = smgBean.getPetitions(interfaceSequences);
		List<Crdn> crdns = importBean.createCrdns(petitions);
		if (crdns.isEmpty()) return 0;

		List<String> intfSeqs = crdns.stream().map(Crdn::getLinkId).toList();

		List<FileInfo> smgFileInfoList = fileBean.getFilesOf("010", intfSeqs.toArray(new String[intfSeqs.size()]));
		Map<String, List<FileInfo>> byInfoKey = smgFileInfoList.stream().collect(Collectors.groupingBy(FileInfo::getInfoKey));

		for (Crdn crdn: crdns) {
			List<FileInfo> files = byInfoKey.get(crdn.getLinkId());

			files.removeIf(item -> item.getMimeType().startsWith("video"));

			for(FileInfo file : files) {
		    	file.setInputStream(file.getInputStream()); //신규 인풋스트림 생성
		    	file.setUrl(""); //인터페이스 첨부파일정보 제거
		    	file.setPath(""); //국민신문고 첨부파일정보 제거
			}

		    crdn.setCvlcptLinkYn("Y");
			crdnBean.create(null, crdn, files);
		}

		importBean.createCvlcpts(petitions);

		return 0;
	}
}