<%#
 Copyright 2013-2021 the original author or authors from the BegCode project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      https://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
package <%= packageName %>.service.mapper;

<%_
const manyListName = ormTool !== 'mybatis' ? 'Set' : 'List';
const manyListType = ormTool !== 'mybatis' ? 'LinkedHashSet' : 'ArrayList';
_%>
<%_ if (databaseType === 'sql' || databaseType === 'mongodb' || databaseType === 'neo4j') { _%>
import <%= packageName %>.domain.Authority;
import <%= packageName %>.repository.AuthorityRepository; // add by wangxin
<%_ } _%>
import <%= packageName %>.domain.<%= user.persistClass %>;
import <%= packageName %>.service.dto.<%= user.adminUserDto %>;
import <%= packageName %>.service.dto.<%= user.dtoClass %>;

import org.springframework.stereotype.Service;

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

import org.mapstruct.BeanMapping;
import org.mapstruct.Mapping;
import org.mapstruct.Named;
/**
 * Mapper for the entity {@link <%= user.persistClass %>} and its DTO called {@link <%= user.dtoClass %>}.
 *
 * Normal mappers are generated using MapStruct, this one is hand-coded as MapStruct
 * support is still in beta, and requires a manual step with an IDE.
 */
@Service
public class UserMapper {
<%_ if (databaseType === 'sql' || databaseType === 'mongodb') { _%>
    // add by wangxin start
    private final AuthorityRepository authorityRepository;

    public UserMapper(AuthorityRepository authorityRepository) {
        this.authorityRepository = authorityRepository;
    }
    // add by wangxin end
<%_ } _%>

    public List<<%= user.dtoClass %>> usersToUserDTOs(List<<%= user.persistClass %>> users) {
        return users.stream()
            .filter(Objects::nonNull)
            .map(this::userToUserDTO)
            .collect(Collectors.toList());
    }

    public <%= user.dtoClass %> userToUserDTO(<%= user.persistClass %> user) {
        return new <%= user.dtoClass %>(user);
    }

    public List<<%= user.adminUserDto %>> usersToAdminUserDTOs(List<<%= user.persistClass %>> users) {
        return users.stream()
            .filter(Objects::nonNull)
            .map(this::userToAdminUserDTO)
            .collect(Collectors.toList());
    }

    public <%= user.adminUserDto %> userToAdminUserDTO(<%= user.persistClass %> user) {
        return new <%= user.adminUserDto %>(user);
    }

    public List<<%= user.persistClass %>> userDTOsToUsers(List<<%= user.adminUserDto %>> userDTOs) {
        return userDTOs.stream()
            .filter(Objects::nonNull)
            .map(this::userDTOToUser)
            .collect(Collectors.toList());
    }

    public <%= user.persistClass %> userDTOToUser(<%= user.adminUserDto %> userDTO) {
        if (userDTO == null) {
            return null;
        } else {
            <%= user.persistClass %> user = new <%= user.persistClass %>();
            user.setId(userDTO.getId());
            user.setLogin(userDTO.getLogin());
            user.setFirstName(userDTO.getFirstName());
            user.setLastName(userDTO.getLastName());
            user.setEmail(userDTO.getEmail());
            <%_ if (databaseType !== 'cassandra') { _%>
            user.setImageUrl(userDTO.getImageUrl());
            <%_ } _%>
            user.setActivated(userDTO.getActivated());
            user.setLangKey(userDTO.getLangKey());
            <%_ if (databaseType === 'sql' || databaseType === 'mongodb' || databaseType === 'neo4j') { _%>
            <%= manyListName%><Authority> authorities = this.authoritiesFromStrings(userDTO.getAuthorities());
            user.setAuthorities(authorities);
            <%_ } _%>
            <%_ if (databaseType === 'cassandra' || databaseType === 'couchbase') { _%>
            Set<String> roles = this.cleanNullStringAuthorities(userDTO.getRoles());
            user.setRoles(roles);
            <%_ } _%>
            return user;
        }
    }

    <%_ if (databaseType === 'sql' || databaseType === 'mongodb' || databaseType === 'neo4j') { _%>

    private <%= manyListName%><Authority> authoritiesFromStrings(<%= manyListName%><String> authoritiesAsString) {
        <%= manyListName%><Authority> authorities = new <%= manyListType%><>();

        if(authoritiesAsString != null){
            authorities = authoritiesAsString.stream().map(string -> {
                /* comment by wangxin
                Authority auth = new Authority();
                auth.setName(string);
                return auth; */
                return authorityRepository.findFirstByCode(string).get(); // add by wangxin
            }).collect(Collectors.to<%= manyListName%>());
        }

        return authorities;
    }
    <%_ } _%>
    <%_ if (databaseType === 'cassandra' || databaseType === 'couchbase') { _%>

    private <%= manyListName%><String> cleanNullStringAuthorities(<%= manyListName%><String> authoritiesAsString) {
        <%= manyListName%><String> authorities = new <%= manyListType%><>();

        if(authoritiesAsString != null) {
            authorities = authoritiesAsString.stream()
                .filter(Objects::nonNull)
                .collect(Collectors.to<%= manyListName%>());
        }

        return authorities;
    }
    <%_ } _%>

    public <%= user.persistClass %> userFromId(<%= user.primaryKey.type %> id) {
        if (id == null) {
            return null;
        }
        <%= user.persistClass %> user = new <%= user.persistClass %>();
        user.setId(id);
        return user;
    }

    @Named("id")
    @BeanMapping(ignoreByDefault = true)
    @Mapping(target = "id", source = "id")
    public <%= user.dtoClass %> toDtoId(<%= user.persistClass %> user) {
        if (user == null) {
            return null;
        }
        <%= user.dtoClass %> userDto = new <%= user.dtoClass %>();
        userDto.setId(user.getId());
        return userDto;
    }

    @Named("idSet")
    @BeanMapping(ignoreByDefault = true)
    @Mapping(target = "id", source = "id")
    public Set<<%= user.dtoClass %>> toDtoIdSet(Set<<%= user.persistClass %>> users) {
        if ( users == null ) {
            return null;
        }

        Set<<%= user.dtoClass %>> userSet = new HashSet<>();
        for ( <%= user.persistClass %> userEntity : users ) {
            userSet.add( this.toDtoId( userEntity ) );
        }

        return userSet;
    }

    @Named("login")
    @BeanMapping(ignoreByDefault = true)
    @Mapping(target = "id", source = "id")
    @Mapping(target = "login", source = "login")
    public <%= user.dtoClass %> toDtoLogin(<%= user.persistClass %> user) {
        if (user == null) {
            return null;
        }
        <%= user.dtoClass %> userDto = new <%= user.dtoClass %>();
        userDto.setId(user.getId());
        userDto.setLogin(user.getLogin());
        return userDto;
    }

    @Named("loginSet")
    @BeanMapping(ignoreByDefault = true)
    @Mapping(target = "id", source = "id")
    @Mapping(target = "login", source = "login")
    public Set<<%= user.dtoClass %>> toDtoLoginSet(Set<<%= user.persistClass %>> users) {
        if ( users == null ) {
            return null;
        }

        Set<<%= user.dtoClass %>> userSet = new HashSet<>();
        for ( <%= user.persistClass %> userEntity : users ) {
            userSet.add( this.toDtoLogin( userEntity ) );
        }

        return userSet;
    }

    @Named("firstName")
    @BeanMapping(ignoreByDefault = true)
    @Mapping(target = "id", source = "id")
    @Mapping(target = "firstName", source = "firstName")
    public UserDTO toDtoFirstName(User user) {
        if (user == null) {
            return null;
        }
        UserDTO userDto = new UserDTO();
        userDto.setId(user.getId());
        userDto.setFirstName(user.getFirstName());
        return userDto;
    }
}
