package com.eactive.eai.rms.onl.loader.service;

import com.eactive.eai.data.DataService;
import com.eactive.eai.data.entity.AbstractEntity;
import com.eactive.eai.data.mapper.GenericMapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

public abstract class DeployService {

    @Transactional
    public  <V extends DeployResource<E>, E extends AbstractEntity<I>, I> void deleteExistsAndSaveAll(List<V> voList, GenericMapper<V, E> mapper, DataService<E, I> dataService) {
        List<E> saveTargetList = voList.stream().map(mapper::toEntity).collect(Collectors.toList());

        /* DeleteAll By RemoveFields */
        voList.stream().map(DeployResource::exampleForRemove).map(dataService::findAll).forEach(dataService::deleteAll);

        /* SaveAll */
        dataService.saveAll(saveTargetList);
    }

    @Transactional
    public  <V extends DeployResource<E>, E extends AbstractEntity<I>, I> void deleteAndSave(V vo, GenericMapper<V, E> mapper, DataService<E, I> dataService) {
        E saveTarget = mapper.toEntity(vo);

        /* Delete By RemoveFields */
        dataService.deleteAll(dataService.findAll(vo.exampleForRemove()));

        /* Save */
        dataService.save(saveTarget);
    }

}
