package net.zstong.awump.dimension;

import lombok.AllArgsConstructor;
import net.zstong.awump.base.entity.AwInstitutionEntity;
import org.hswebframework.ezorm.rdb.mapping.ReactiveRepository;
import org.hswebframework.web.api.crud.entity.GenericEntity;
import org.hswebframework.web.authorization.Dimension;
import org.hswebframework.web.authorization.DimensionProvider;
import org.hswebframework.web.authorization.DimensionType;
import org.hswebframework.web.system.authorization.api.entity.DimensionUserEntity;
import org.hswebframework.web.system.authorization.defaults.service.DefaultDimensionUserService;
import org.hswebframework.web.system.authorization.defaults.service.terms.DimensionTerm;
import org.reactivestreams.Publisher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Collections;

@AllArgsConstructor
@Component
public class InstitutionDimensionProvider extends GenericEntity<String> implements DimensionProvider {

    @Autowired
    private ReactiveRepository<AwInstitutionEntity, String> repository;

    @Autowired
    private DefaultDimensionUserService dimensionUserService;


    protected Flux<? extends Dimension> convertToDimension(Publisher<AwInstitutionEntity> source) {
        return Flux.from(source).flatMap(this::convertToDimension);
    }

    protected Mono<Dimension> convertToDimension(AwInstitutionEntity entity) {
        return Mono.just(entity.toDimension(true));
    }

    @Override
    public Flux<? extends DimensionType> getAllType() {
        return Flux.just(InstitutionDimensionType.institution);
    }


    @Override
    public Mono<? extends Dimension> getDimensionById(DimensionType dimensionType, String s) {
        if (!dimensionType.isSameType(InstitutionDimensionType.institution)) {
            return Mono.empty();
        }
        return repository
            .findById(s)
            .as(this::convertToDimension)
            .singleOrEmpty();
    }

    @Override
    public Flux<String> getUserIdByDimensionId(String s) {
        return dimensionUserService
            .createQuery()
            .where(DimensionUserEntity::getDimensionId, s)
            .and(DimensionUserEntity::getDimensionTypeId, InstitutionDimensionType.institution.getId())
            .fetch()
            .map(DimensionUserEntity::getUserId);

    }

    @Override
    public Flux<? extends Dimension> getDimensionByUserId(String s) {
        return DimensionTerm
            .inject(repository.createQuery(), "id", InstitutionDimensionType.institution.getId(), Collections.singletonList(s))
            .fetch()
            .as(this::convertToDimension)
            ;
    }

}
