package com.scene.ingsta.services;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.scene.ingsta.beans.Notify;
import com.scene.ingsta.beans.Scene;
import com.scene.ingsta.core.Utility;
import com.scene.ingsta.repositories.NotifyRepository;
import com.scene.ingsta.repositories.SceneRepository;

/**
 * <h1>
 * 
 * 씬 서비스
 * 
 * </h1>
 * 
 * <p>
 * 
 * 씬 콩
 * 
 * </p>
 * 
 * 엔티티 빈
 * 
 * <ul>
 * <li></li>
 * </ul>
 * 
 * @author parkwonsuk
 * 
 * @version 0.0.1-SNAPSHOT
 * 
 */
@Service
public class SceneService {

	/**
	 * Logger
	 */
	@SuppressWarnings("unused")
	private static final Logger LOGGER = LoggerFactory.getLogger(SceneService.class);

	/**
	 * 씬 리포지토리
	 */
	@Autowired
	private SceneRepository sceneRepository;

	/**
	 * 알림(notify)리포지토리
	 */
	@Autowired
	private NotifyRepository notifyRepository;

	/**
	 * 씬 서비스
	 */
	public SceneService() {

	}

	/**
	 * 씬 목록
	 * 
	 * @param condition
	 *            잉 아이디와 요청한 씬 번호
	 * @return 씬 목록 과 카운트, 씬의 잉스타 목록
	 */
	@Transactional
	public Map<String, Object> listScene(HashMap<String, Object> condition) {

		Map<String, Object> result = new HashMap<String, Object>();
		int ingId = Integer.parseInt(condition.get("ingId").toString());

		result.put("count", sceneRepository.count(condition));
		result.put("list", sceneRepository.scenelist(ingId));

		return result;
	}

	/**
	 * 하나의 씬
	 * 
	 * @param condition
	 *            잉 아이디와 요청한 씬 번호
	 * @return 하나의 씬
	 */
	@Transactional
	public Object getScene(HashMap<String, Object> condition) {

		return sceneRepository.get(condition);
	}

	/**
	 * 씬 추가
	 * 
	 * @param scene
	 *            추가 요청할 씬
	 * @return 씬 추가
	 */
	@Transactional
	public Object addScene(Scene scene, String ingWrtierId, String message, String state) {
		String convertMsg = Utility.convertEscapeChar(scene.getContents());
		scene.setContents(convertMsg);
		int flag = sceneRepository.add(scene);
		

		if (flag > 0 && !(scene.getIngstaId().equals(ingWrtierId))) {
			Notify bean = new Notify();
			bean.setIngId(scene.getIngId());
			bean.setSenderId(scene.getIngstaId());
			bean.setReceiverId(ingWrtierId);
			bean.setState(state);
			bean.setMessage(message);
			int notiResult = notifyRepository.add(bean);

			LOGGER.debug("notiInsertResult {}", notiResult);
		}

		return flag;
	}

	/**
	 * 씬 수정
	 * 
	 * @param scene
	 *            수정 요청할 씬
	 * @return 씬 수정
	 */
	@Transactional
	public Object updateScene(Scene scene) {
		String convertMsg = Utility.convertEscapeChar(scene.getContents());
		scene.setContents(convertMsg);

		return sceneRepository.update(scene);
	}

	/**
	 * 씬 삭제
	 * 
	 * @param scene
	 *            삭제 요청할 씬
	 * @return 씬 삭제
	 */
	@Transactional
	public Object removeScene(Scene scene) {

		return sceneRepository.remove(scene);
	}

}
