package com.izouma.jiashanxia.repo;

import com.izouma.jiashanxia.domain.User;
import com.izouma.jiashanxia.dto.PageQuery;
import com.izouma.jiashanxia.enums.AuthorityName;
import com.izouma.jiashanxia.security.Authority;
import com.izouma.jiashanxia.utils.JpaUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.test.context.junit4.SpringRunner;

import javax.persistence.criteria.*;
import java.util.Collections;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserRepoTest {
    @Autowired
    private UserRepo userRepo;

    @Test
    public void testUser() {
        User user = User.builder()
                .username("root")
                .password(new BCryptPasswordEncoder().encode("123456"))
                .avatar("")
                .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_ADMIN)))
                .build();
        userRepo.save(user);
    }

    @Test
    public void createUser() {

        User user = userRepo.findByUsernameAndDelFalse("root");
//        user.setPassword(new BCryptPasswordEncoder().encode("123456"));
        user.setAuthorities(Collections.singleton(Authority.builder().name("ROLE_ADMIN").build()));
        userRepo.save(user);
    }

    @Test
    public void findAllByAuthoritiesContains() {
        List<User> list = userRepo.findAllByAuthoritiesContainsAndDelFalse(Authority.builder()
                .name("ROLE_ADMIN")
                .build());
        System.out.println(list);
    }

    @Test
    public void test() {
        PageQuery pageQuery = new PageQuery();
        Authority authority = Authority.get(AuthorityName.ROLE_CREATOR);
        Page<User> all = userRepo.findAll(((root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> and = JpaUtils.toPredicates(pageQuery, User.class, root, criteriaQuery, criteriaBuilder);

            SetJoin<User, Authority> join = root.join(root.getModel()
                    .getSet("authorities", Authority.class), JoinType.LEFT);
            and.add(join.in(authority));
            return criteriaBuilder.and(and.toArray(new Predicate[0]));
        }), JpaUtils.toPageRequest(pageQuery));
        all.getContent().forEach(System.out::println);
    }
}
