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

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import cokr.xit.fims.cmmn.dao.LinkMapper;
import cokr.xit.foundation.component.AbstractBean;
import cokr.xit.foundation.data.DataObject;

@Component("linkBean")
public class LinkBean extends AbstractBean {

	@Resource(name = "linkMapper")
	private LinkMapper linkMapper;

	public boolean insertElectronicNoticeSndng(DataObject masterInfo, List<DataObject> detailInfos) {

		int effected = linkMapper.insertElectronicNoticeSndngMaster(masterInfo);
		if(effected != 1) {
			throw new RuntimeException("발송 마스터 등록 오류");
		}

		effected = 0;
		for(int i=0; i < detailInfos.size(); i++) {
			detailInfos.get(i).set("unitySndngMastrId", masterInfo.string("unitySndngMastrId"));
			effected = linkMapper.insertElectronicNoticeSndngDetail(detailInfos.get(i));
			if(effected != 1) {
				throw new RuntimeException("발송 상세 등록 오류");
			}
		}

		if(effected != 1) {
			throw new RuntimeException("발송 상세 등록 오류");
		}

		return true;
	}

	public String makeJson(String jsonTemplate, Map<String, String> extractedText, List<String> crdnPhotoBase64) {
		String result = jsonTemplate;

		Iterator<String> it = extractedText.keySet().iterator();
		while(it.hasNext()) {
			String key = it.next();
			String value = extractedText.get(key);

			result = result.replaceAll("^##"+key+"##$", value);
		}


		int i=0;
		if(result.contains("##photo0##")) {
			boolean flag = true;
			while(flag) {
				String value = "";
				if((i+1) <= crdnPhotoBase64.size()) {
					value = crdnPhotoBase64.get(i);
				}
				result = result.replaceAll("^##photo"+i+"##$", value);

				i++;
				if(!result.contains("##photo"+i+"##")) {
					flag = false;
				}
			}
		}

		return result;
	}
}
