package eu.eudat.data.dao.entities.security;

import eu.eudat.data.dao.DatabaseAccess;
import eu.eudat.data.dao.databaselayer.service.DatabaseService;
import eu.eudat.data.entities.Credential;
import eu.eudat.queryable.QueryableList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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


@Component("credentialDao")
public class CredentialDaoImpl extends DatabaseAccess<Credential> implements CredentialDao {

    @Autowired
    public CredentialDaoImpl(DatabaseService<Credential> databaseService) {
        super(databaseService);
    }

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

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

    @Override
    public Credential getLoggedInCredentials(String username, String secret, Integer provider) {
        return this.getDatabaseService().getQueryable(Credential.class).where(((builder, root) ->
                builder.and(
                        builder.equal(root.get("publicValue"), username),
                        builder.equal(root.get("secret"), secret),
                        builder.equal(root.get("provider"), provider)
                ))).getSingleOrDefault();
    }

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

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

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

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