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

import com.bocloud.ims.entity.common.MapBuilder;
import com.bocloud.ims.entity.resource.hmc.HmdServerVirtualSwitch;
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 HmdServerVirtualSwitchRepository extends HmdGenericDao<HmdServerVirtualSwitch> {

    @Lookup protected abstract HmdServerRepository serverRepository();
    @Lookup protected abstract HmdServerVirtualNetworkRepository serverVirtualNetworkRepository();

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

    @Override
    public void extra(HmdServerVirtualSwitch virtualSwitch) {
        Optional.of(virtualSwitch).map(HmdServerVirtualSwitch::getServerId).map(this.serverRepository()::getById).ifPresent(virtualSwitch::setServer);
        Optional.of(virtualSwitch).map(HmdServerVirtualSwitch::getId).map(this.serverVirtualNetworkRepository()::listBySwitchId).ifPresent(virtualSwitch::setVirtualNetworks);
    }

    public List<HmdServerVirtualSwitch> listByServerId(long serverId) {
        return this.search(Collections.singletonMap("a.server_id", serverId));
    }

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

    public HmdServerVirtualSwitch getByUuid(String uuid) {
        return this.search(Collections.singletonMap("a.uuid", uuid)).stream().findFirst().orElse(null);
    }

    public HmdServerVirtualSwitch getBySwitchId(long serverId, long switchId) {
        Map<String, Object> params = MapBuilder.init()
            .put("a.server_id", serverId)
            .put("a.switch_id", switchId)
            .get();
        return this.search(params).stream().findFirst().orElse(null);
    }

    public List<HmdServerVirtualSwitch> search(long serverId, String bridgeName) {
        Map<String, Object> map = MapBuilder.init()
            .put("a.server_id", serverId)
            .put("a.name", bridgeName)
            .get();
        return this.search(map);
    }

}
