package com.eactive.eai.rms.onl.manage.adapter.adapter.mapper;

import java.util.Optional;

import org.apache.commons.lang3.StringUtils;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.AfterMapping;
import org.mapstruct.MappingTarget;

import org.springframework.beans.factory.annotation.Autowired;
import com.eactive.eai.data.entity.onl.adapter.AdapterGroup;
import com.eactive.eai.data.mapper.BaseMapperConfig;
import com.eactive.eai.data.mapper.GenericMapper;
import com.eactive.apim.portal.monitoringcode.entity.MonitoringCodeId;
import com.eactive.eai.rms.data.entity.man.monitoringCode.service.MonitoringCodeService;
import com.eactive.eai.rms.onl.manage.adapter.adapter.ui.AdapterGroupUI;

@Mapper(config = BaseMapperConfig.class, uses = { AdapterUIMapper.class })
public abstract class AdapterGroupUIMapper implements GenericMapper<AdapterGroupUI, AdapterGroup> {

	@Autowired
	private MonitoringCodeService monitoringCodeService;

	@Mapping(source = "adapterData", target = "adapters")
	@Override
	public abstract AdapterGroup toEntity(AdapterGroupUI vo);

	@Mapping(source = "adapterData", target = "adapters")
	public abstract AdapterGroup updateEntity(AdapterGroupUI vo, @MappingTarget AdapterGroup adapterGroup);

	@Mapping(source = "adapters", target = "adapters", ignore = true)
	public abstract AdapterGroupUI toVoWithoutChildrenMapping(AdapterGroup entity);

	@AfterMapping
	public void setAdapterInstitutionName(@MappingTarget AdapterGroupUI adapterGroupUI) {
		Optional.ofNullable(adapterGroupUI.getAdptrinsticode()).filter(StringUtils::isNotBlank).map(code -> {
			try {
				return monitoringCodeService.findCodenameById(new MonitoringCodeId("ADPTR_DESC", code));
			} catch (Exception e) {
				return null;
			}
		}).ifPresent(adapterGroupUI::setAdptrinstiName);
	}

	@AfterMapping
	public void setAdapterGroup(@MappingTarget AdapterGroup adapterGroup) {
		if (adapterGroup.getAdapters() != null) {
			adapterGroup.getAdapters().forEach(adapter -> adapter.setAdapterGroup(adapterGroup));
		}
	}
}
