package ru.ulstu.user.service;

import org.springframework.stereotype.Service;
import ru.ulstu.user.model.*;
import ru.ulstu.user.model.*;
import ru.ulstu.user.repository.UserRoleRepository;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserMapper {
    private final UserRoleRepository userRoleRepository;

    public UserMapper(UserRoleRepository userRoleRepository) {
        this.userRoleRepository = userRoleRepository;
    }

    public Set<UserRole> rolesFromDto(Set<UserRoleDto> strings) {
        return Optional.ofNullable(strings).orElse(Collections.emptySet()).stream()
                .filter(Objects::nonNull)
                .map(role -> userRoleRepository.findOne(role.getId().toString()))
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
    }

    public UserDto userEntityToUserDto(User userEntity) {
        if (userEntity == null) {
            return null;
        }
        return new UserDto(userEntity);
    }

    public UserListDto userEntityToUserListDto(User userEntity) {
        if (userEntity == null) {
            return null;
        }
        return new UserListDto(userEntity);
    }

    public List<UserListDto> userEntitiesToUserListDtos(List<User> userEntities) {
        return userEntities.stream()
                .filter(Objects::nonNull)
                .map(this::userEntityToUserListDto)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }

    public User userDtoToUserEntity(UserDto userDto) {
        if (userDto == null) {
            return null;
        }
        final User user = new User();
        user.setId(userDto.getId());
        user.setLogin(userDto.getLogin());
        user.setFirstName(userDto.getFirstName());
        user.setLastName(userDto.getLastName());
        user.setEmail(userDto.getEmail());
        user.setActivated(userDto.isActivated());
        final Set<UserRole> roles = this.rolesFromDto(userDto.getRoles());
        if (!roles.isEmpty()) {
            user.setRoles(roles);
        }
        return user;
    }
}
