package com.bocloud.ims.repository.resource.hmc;

import com.bocloud.cmp.model.hmc.enums.VirtualAdapterTargetType;
import com.bocloud.ims.entity.common.MapBuilder;
import com.bocloud.ims.entity.resource.hmc.HmdVirtualIoAdapter;
import org.springframework.beans.factory.annotation.Lookup;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Repository
public abstract class HmdVirtualIoAdapterRepository extends HmdGenericDao<HmdVirtualIoAdapter> {

    public HmdVirtualIoAdapterRepository(JdbcTemplate jdbcTemplate, NamedParameterJdbcTemplate npJdbcTemplate) {
        super(jdbcTemplate, npJdbcTemplate);
    }

    @Lookup protected abstract HmdPartitionRepository partitionRepository();
    @Lookup protected abstract HmdProfileRepository profileRepository();
    @Lookup protected abstract HmdServerIoAdapterRepository serverIoAdapterRepository();

    @Override
    public void extra(HmdVirtualIoAdapter adapter) {
        Optional.of(adapter).map(HmdVirtualIoAdapter::getTargetType).map(VirtualAdapterTargetType::valueOf).ifPresent(targetType -> {
            switch (targetType) {
                case PARTITION: {
                    Optional.of(adapter).map(HmdVirtualIoAdapter::getTargetId).map(this.partitionRepository()::getById).ifPresent(adapter::setPartition);
                    break;
                }
                case PROFILE: {
                    Optional.of(adapter).map(HmdVirtualIoAdapter::getTargetId).map(this.profileRepository()::getById).ifPresent(adapter::setProfile);
                    break;
                }
                default:
                    throw new IllegalArgumentException("未知的类型：" + targetType.name());
            }
        });
        Optional.of(adapter).map(HmdVirtualIoAdapter::getAdapterId).map(this.serverIoAdapterRepository()::getById).ifPresent(adapter::setIoAdapter);
    }

    public List<HmdVirtualIoAdapter> listByPartitionId(long partitionId) {
        Map<String, Object> map = MapBuilder.init()
            .put("a.target_id", partitionId)
            .put("a.type", VirtualAdapterTargetType.PARTITION.name())
            .get();
        return this.search(map);
    }

    public List<HmdVirtualIoAdapter> listByProfileId(long profileId) {
        Map<String, Object> map = MapBuilder.init()
            .put("a.target_id", profileId)
            .put("a.type", VirtualAdapterTargetType.PROFILE.name())
            .get();
        return this.search(map);
    }

    public HmdVirtualIoAdapter getById(long id) {
        return this.search(Collections.singletonMap("a.id", id)).stream().findFirst().orElse(null);
    }

    @Override
    public void clear(long id) {
        this.delete(id);
    }

}
