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

import com.bocloud.ims.entity.resource.hmc.HmdProfileHea;
import com.bocloud.ims.entity.resource.hmc.HmdServerHea;
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 HmdProfileHeaRepository extends HmdGenericDao<HmdProfileHea> {

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

    @Lookup protected abstract HmdProfileRepository profileRepository();
    @Lookup protected abstract HmdServerHeaRepository serverHeaRepository();

    @Override
    public void extra(HmdProfileHea hea) {
        Optional.of(hea).map(HmdProfileHea::getProfileId).map(this.profileRepository()::getById).ifPresent(hea::setProfile);
        Optional.of(hea).map(HmdProfileHea::getHeaId).map(this.serverHeaRepository()::getById).ifPresent(hea::setHea);
    }

    public List<HmdProfileHea> listByProfileId(long profileId) {
        return this.search(Collections.singletonMap("a.profile_id", profileId));
    }

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

    @Override
    public void convertInstance(final HmdProfileHea srcT, final HmdProfileHea desT) {
        Optional<HmdServerHea> hea = Optional.of(srcT).map(HmdProfileHea::getHea).map(HmdServerHea::getUuid).map(this.serverHeaRepository()::getByUuid);
        hea.map(HmdServerHea::getId).ifPresent(srcT::setHeaId);
        hea.ifPresent(srcT::setHea);

        this.copy(srcT, desT);
    }
}
