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

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

    @Lookup protected abstract HmdServerRepository serverRepository();

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

    @Override
    public void extra(HmdServerIoAdapter adapter) {
        Optional.of(adapter).map(HmdServerIoAdapter::getServerId).map(this.serverRepository()::getById).ifPresent(adapter::setServer);
    }

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

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

    public HmdServerIoAdapter getByAdapterId(long serverId, long adapterId) {
        Map<String, Object> map = MapBuilder.init().put("a.server_id", serverId).put("a.adapter_id", adapterId).get();
        return this.search(map).stream().findFirst().orElse(null);
    }

}
