package com.eactive.eai.rms.data.entity.man.user;


import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eactive.eai.data.jpa.AbstractDataService;


@Service
@Transactional(transactionManager = "transactionManagerForEMS")
public class UserServiceTypeService
						extends
						AbstractDataService<UserServiceType, UserServiceTypeId, UserServiceTypeRepository> {

	public void insertUserServiceType(String userId, String serviceType) {
		UserServiceTypeId id = new UserServiceTypeId(userId, serviceType);
		Optional<UserServiceType> existingServiceType = repository.findById(id);

		if (!existingServiceType.isPresent()) {
			UserServiceType userServiceType = new UserServiceType();
			userServiceType.setId(id);
			repository.save(userServiceType);
		}

	}


	public void deleteAllByUserId(String userId) {
		repository.deleteAll(findByUserId(userId));

	}


	public String selectLoginUseServiceTypes(String userId) {
		List<UserServiceType> serviceTypes = selectUserServiceTypeList(userId);

		return serviceTypes.stream()
								.map(userServiceType -> userServiceType.getId()
														.getUseServiceType())
								.sorted(Comparator.reverseOrder())
								.collect(Collectors.joining(","));
	}


	public List<UserServiceType> findByUserId(String userId) {
		QUserServiceType qUserServiceType = QUserServiceType.userServiceType;
		List<UserServiceType> list = new ArrayList<>();
		repository.findAll(qUserServiceType.id.userId.eq(userId))
								.forEach(list::add);
		return list;
	}


	public List<UserServiceType> selectUserServiceTypeList(String userId) {
		return StreamSupport
								.stream(repository.findAll(
														QUserServiceType.userServiceType.id.userId
																				.eq(userId))
														.spliterator(), false)
								.collect(Collectors.toList());
	}

}
