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

import com.bocloud.ims.entity.resource.hmc.HmdPartition;
import com.bocloud.ims.entity.resource.hmc.HmdServerHeaLogicalPort;
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.Optional;

@Repository
public abstract class HmdServerHeaLogicalPortRepository extends HmdGenericDao<HmdServerHeaLogicalPort> {

    @Lookup protected abstract HmdPartitionRepository partitionRepository();
    @Lookup protected abstract HmdServerHeaRepository serverHeaRepository();

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

    @Override
    public void extra(HmdServerHeaLogicalPort port) {
        Optional.of(port).map(HmdServerHeaLogicalPort::getHeaId).map(this.serverHeaRepository()::getById).ifPresent(port::setHea);
        Optional.of(port).map(HmdServerHeaLogicalPort::getPartitionId).map(this.partitionRepository()::getById).ifPresent(port::setPartition);
    }

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

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

    @Override
    public void convertInstance(final HmdServerHeaLogicalPort srcT, final HmdServerHeaLogicalPort desT) {
        Optional<HmdPartition> partition = Optional.of(srcT).map(HmdServerHeaLogicalPort::getPartition).map(HmdPartition::getUuid).map(this.partitionRepository()::getByUuid);
        partition.map(HmdPartition::getId).ifPresent(srcT::setPartitionId);
        partition.ifPresent(srcT::setPartition);

        this.copy(srcT, desT);
    }
}
