package com.eactive.eai.rms.common.acl.user;

import java.util.List;
import java.util.stream.Collectors;

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

import com.eactive.eai.rms.common.acl.user.ui.UserServicetypeUI;
import com.eactive.eai.rms.common.base.BaseService;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.eactive.eai.rms.data.entity.man.user.UserServiceType;
import com.eactive.eai.rms.data.entity.man.user.UserServiceTypeId;
import com.eactive.eai.rms.data.entity.man.user.UserServiceTypeService;

@Service
@Transactional(transactionManager = "transactionManagerForEMS")
public class ServiceTypeManService extends BaseService {

	@Autowired
	private UserServiceTypeService userServiceTypeService;

	public List<UserServicetypeUI> selectUserServiceTypeList(String userId, String targetGridYn) {
		List<UserServiceType> userServiceTypeList = userServiceTypeService.selectUserServiceTypeList(userId);
		List<UserServicetypeUI> allServiceTypes = getDatasourceList();

		return allServiceTypes.stream().filter(ui -> isMatchTargetServiceTypes(userServiceTypeList, ui, targetGridYn))
				.collect(Collectors.toList());
	}

	private List<UserServicetypeUI> getDatasourceList() {
		
		return DataSourceTypeManager.getDynamicDataSourceTypes().stream()
				.map(datasource -> {
					
				UserServicetypeUI ui = new UserServicetypeUI();
				ui.setUseServiceType(datasource.getName());
				ui.setDesc(datasource.getText());
				return ui;
				
		}).collect(Collectors.toList());
	}

	private boolean isMatchTargetServiceTypes(List<UserServiceType> userServiceTypeList, UserServicetypeUI ui,
			String targetGridYn) {
		boolean userHasServiceType = userServiceTypeList.stream()
				.anyMatch(serviceType -> serviceType.getId().getUseServiceType().equals(ui.getUseServiceType()));

		return "Y".equals(targetGridYn) ? userHasServiceType : !userHasServiceType;
	}

	public void transactionUserServiceType(String userId, List<UserServicetypeUI> userServicetypeUIs) {
		userServicetypeUIs.forEach(ui -> {
			UserServiceTypeId userServiceTypeId = new UserServiceTypeId(userId, ui.getUseServiceType());

			if ("true".equals(ui.getChk())) {
				UserServiceType userServiceType = new UserServiceType();
				userServiceType.setId(userServiceTypeId);
				userServiceTypeService.save(userServiceType);

			} else if ("false".equals(ui.getChk())) {
				userServiceTypeService.deleteById(userServiceTypeId);
			}
		});
	}

}
