package nlib.bbs.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import nlib.bbs.service.ArticleVO;
import nlib.bbs.service.AttachFileService;
import nlib.bbs.service.AttachFileVO;
import nlib.bbs.service.QnaService;
import nlib.util.UUID;

@Service("qnaService")
public class QnaServiceImpl extends BoardServiceImpl implements QnaService
{
	static Logger log = LoggerFactory.getLogger(QnaServiceImpl.class);
	
	@Resource(name="qnaDAO")
	QnaDAO qnaDAO;
	
	@Resource(name="attachFileService")
	AttachFileService attachFileService;

	@Override
	public BoardDAO getBoardDAO() {
		return qnaDAO;
	}


	/**
	 * Q&A 게시글을 등록한다. 
	 * 
	 * @param reqVO
	 * @return
	 */
	public ArticleVO insertArticle(ArticleVO articleVO) throws Exception {
		articleVO.setArticleId(UUID.getNlibCommonID("NQ", 35));
		int ret = qnaDAO.insertArticle(articleVO);
		
		if(ret < 1) {
			throw new Exception("등록에 실패하였습니다.");
		}
		
		articleVO.setResultCode("S001");
		
		if(articleVO.getAttachFileCnt() > 0) {
			int savedCnt = 0;
			List<AttachFileVO> attachFileList = articleVO.getAttachFiles();
			for(int i=0; i<attachFileList.size(); i++) {
				AttachFileVO attachFileVO = attachFileList.get(i);
				int retAttFile = attachFileService.insertAttachFile(attachFileVO);
				savedCnt += retAttFile;
				if(retAttFile < 1) {
					log.error("insertArticle > 첨부파일 등록에 실패하였습니다 : " + attachFileVO.getFileName());
				}
			}
			
			if(savedCnt != articleVO.getAttachFileCnt()) {
				articleVO.setResultMessage(String.format("총 %d개 파일 중 %개 파일만 정상등록되었습니다.", articleVO.getAttachFileCnt(), savedCnt));
			}
		}
		
		return articleVO;
	}

	/**
	 * Q&A 게시글을 수정한다. 
	 * 
	 * @param reqVO
	 * @return
	 */
	public int updateArticle(ArticleVO articleVO) {
		return qnaDAO.updateArticle(articleVO);
	}

	/**
	 * Q&A 게시글을 삭제한다.
	 *  
	 * @param reqVO
	 * @return
	 */
	public int deleteArticle(ArticleVO articleVO) {
		return qnaDAO.deleteArticle(articleVO);
	}
	
}