package eu.eudat.data.dao.entities;

import eu.eudat.data.dao.DatabaseAccess;
import eu.eudat.data.dao.criteria.UserRoleCriteria;
import eu.eudat.data.dao.databaselayer.service.DatabaseService;
import eu.eudat.data.entities.UserInfo;
import eu.eudat.data.entities.UserRole;
import eu.eudat.queryable.QueryableList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;


@Component("userRoleDao")
public class UserRoleDaoImpl extends DatabaseAccess<UserRole> implements UserRoleDao {

    @Autowired
    public UserRoleDaoImpl(DatabaseService<UserRole> databaseService) {
        super(databaseService);
    }

    @Override
    public UserRole createOrUpdate(UserRole item) {
        return this.getDatabaseService().createOrUpdate(item, UserRole.class);
    }

    @Override
    public UserRole find(UUID id) {
        return this.getDatabaseService().getQueryable(UserRole.class).where((builder, root) -> builder.equal(root.get("id"), id)).getSingleOrDefault();
    }

    @Override
    public List<UserRole> getUserRoles(UserInfo userInfo) {
        return this.getDatabaseService().getQueryable(UserRole.class).where((builder, root) -> builder.equal(root.get("userInfo"), userInfo)).toList();
    }

    @Override
    public void delete(UserRole item) {
        this.getDatabaseService().delete(item);
    }

    @Override
    public QueryableList<UserRole> getWithCriteria(UserRoleCriteria criteria) {
        QueryableList<UserRole> query = this.getDatabaseService().getQueryable(UserRole.class);
        if (criteria.getLike() != null)
            query.where((builder, root) -> builder.equal(root.get("userInfo").get("name"), criteria.getLike()));
        if (criteria.getAppRoles() != null && !criteria.getAppRoles().isEmpty())
            query.where((builder, root) -> root.get("role").in(criteria.getAppRoles()));
        return query;
    }

    @Override
    public QueryableList<UserRole> asQueryable() {
        return this.getDatabaseService().getQueryable(UserRole.class);
    }

    @Async
    @Override
    public CompletableFuture<UserRole> createOrUpdateAsync(UserRole item) {
        return CompletableFuture.supplyAsync(() -> this.createOrUpdate(item));
    }

    @Override
    public UserRole find(UUID id, String hint) {
        throw new UnsupportedOperationException();
    }
}
