package com.eactive.eai.rms.onl.manage.serviceinfo.subdefault;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eactive.eai.rms.data.entity.onl.stdmessage.SubExtendedColumnDefinition;
import com.eactive.eai.rms.data.entity.onl.stdmessage.SubExtendedColumnDefinitionService;
import com.eactive.eai.rms.onl.common.exception.EMSRuntimeException;

@Service
@Transactional
public class SubDefaultManService {

	@Autowired
	private SubExtendedColumnDefinitionService subExtendedColumnDefinitionService;

	@Autowired
	private SubExtendedColumnDefinitionUIMapper subExtendedColumnDefinitionUIMapper;

	public Page<SubExtendedColumnDefinitionUI> selectList(Pageable pageable, String searchColumnName,
			String searchColumnDesc) {
		return subExtendedColumnDefinitionService
				.findAll(pageable, searchColumnName, searchColumnDesc)
				.map(subExtendedColumnDefinitionUIMapper::toVo);
	}

	public List<Map<String, Object>> selectListToExcel(String searchColumnName, String searchColumnDesc) {
		return subExtendedColumnDefinitionService
				.findAll(Pageable.unpaged(), searchColumnName, searchColumnDesc)
				.map(e -> {
					Map<String, Object> map = new HashMap<>();

					map.put("COLUMNNAME", e.getColumnName());
					map.put("COLUMNDESC", e.getColumnDesc());
					map.put("COLUMNLENGTH", e.getColumnLength());
					map.put("ISKEY", e.getIsKey());
					map.put("ISINTERFACE", e.getIsInterface());

					return map;
				})
				.getContent();
	}

	public SubExtendedColumnDefinitionUI selectDetail(String columnName) {
		SubExtendedColumnDefinition extendedColumnDefinition = subExtendedColumnDefinitionService.getById(columnName);
		return subExtendedColumnDefinitionUIMapper.toVo(extendedColumnDefinition);
	}

	public void insert(SubExtendedColumnDefinitionUI extendedColumnDefinitionUI) {

		if (subExtendedColumnDefinitionService.existsById(extendedColumnDefinitionUI.getColumnName())) {
			throw new EMSRuntimeException("이미 존재하는 컬럼명입니다.");
		}

		SubExtendedColumnDefinition extendedColumnDefinition = subExtendedColumnDefinitionUIMapper
				.toEntity(extendedColumnDefinitionUI);
		subExtendedColumnDefinitionService.save(extendedColumnDefinition);
	}

	public void update(SubExtendedColumnDefinitionUI extendedColumnDefinitionUI) {

		SubExtendedColumnDefinition extendedColumnDefinition = subExtendedColumnDefinitionService
				.getById(extendedColumnDefinitionUI.getColumnName());

		subExtendedColumnDefinitionUIMapper.updateEntity(extendedColumnDefinitionUI, extendedColumnDefinition);
		subExtendedColumnDefinitionService.save(extendedColumnDefinition);
	}

	public void delete(String columnName) {
		subExtendedColumnDefinitionService.deleteById(columnName);
	}

}
