package com.eactive.eai.rms.onl.manage.circuitbreaker;

import java.util.Optional;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
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.data.entity.onl.circuitbreaker.CircuitBreakerConfig;
import com.eactive.eai.rms.common.base.BaseService;
import com.eactive.eai.rms.common.combo.ComboService;
import com.eactive.eai.rms.data.entity.onl.circuitbreaker.CircuitBreakerService;
import com.eactive.eai.rms.data.entity.onl.circuitbreaker.CircuitBreakerServiceDto;

@Service
public class CircuitBreakerManService extends BaseService {

	@Autowired
	@Qualifier("comboService")
	public ComboService comboService;

	@Autowired
	private CircuitBreakerService service;

	@Autowired
	private CircuitBreakerManMapper mapper;

	// 어댑터 유량제어
	public Page<CircuitBreakerManUI> selectList(Pageable pageable, String searchName) {
		Page<CircuitBreakerServiceDto> dtoList = service.findAllForInterface(pageable, searchName);
		return dtoList.map(mapper::toVo);
	}

	public CircuitBreakerManUI selectDetail(String id) {
		CircuitBreakerServiceDto dto = service.findByIdForInterface(id);
		return mapper.toVo(dto);
	}

	@Transactional
	public void merge(CircuitBreakerManUI ui) {
		ui.setCbreakerType(CircuitBreakerService.APIID_TYPE);
		Optional<CircuitBreakerConfig> circuitBreakerConfigOptional;
		if(StringUtils.isNotEmpty(ui.getCbreakerId()))
			circuitBreakerConfigOptional = service.findById(ui.getCbreakerId());
		else 
			circuitBreakerConfigOptional = Optional.empty();
		
		CircuitBreakerConfig entity = null;
		if (circuitBreakerConfigOptional.isPresent()) {
			entity = circuitBreakerConfigOptional.get();
			mapper.updateToEntity(ui, entity);
		} else {
			entity = mapper.toEntity(ui);
			entity.setCbreakerId(null);
		}
		entity = service.save(entity);
		ui.setCbreakerId(entity.getCbreakerId());
		
	}

	public void delete(String id) {
		service.deleteById(id);
	}
	
	
}
