package com.capgemini.reports.teamcenter.resolution.structureservice.explorer;

import com.capgemini.framework.teamcenter.authent.TcSession;
import com.capgemini.framework.teamcenter.exceptions.EmptyNomenclatureException;
import com.capgemini.framework.teamcenter.resolution.filtering.TcTypeInclusionFilter;
import com.capgemini.reports.bomlineholder.BOMLineHolder;
import com.capgemini.reports.bomlineholder.BOMLineHolderHelper;
import com.capgemini.reports.exceptions.InvalidInputException;
import com.capgemini.reports.exceptions.MalformedNomenclatureException;
import com.capgemini.reports.exceptions.NotFoundException;
import com.capgemini.reports.teamcenter.resolution.IBOMLineExplorer;
import com.capgemini.reports.teamcenter.resolution.structureservice.SingleStructureServiceCaller.SingleLevelExpander;
import lombok.extern.slf4j.Slf4j;

import static com.capgemini.framework.teamcenter.object.types.SnecmaObjectTypes.PART_AERO_REVISION;
import static com.capgemini.framework.teamcenter.object.types.SnecmaObjectTypes.RF_GENERIC_REVISION;

/**
 * This class is an {@link IBOMLineExplorer} using a {@link SingleLevelExpander}.<br/>
 * This class can locate and return the Part Number of a Generic (found below the RF Generic of said Generic).
 */
@Slf4j
public class PartNumberFinder implements IBOMLineExplorer {

    @Override
    public BOMLineHolder explore(TcSession session, final SingleLevelExpander expander, final BOMLineHolder genericBom)
            throws InvalidInputException, MalformedNomenclatureException, EmptyNomenclatureException {
        try {
            BOMLineHolder expandedGenericBom = expander.expand(genericBom, new TcTypeInclusionFilter(RF_GENERIC_REVISION));
            BOMLineHolder rfGenericBom = BOMLineHolderHelper.findRfGenericBL(expandedGenericBom);
            BOMLineHolder expandedRfGenericBom = expander.expand(rfGenericBom, new TcTypeInclusionFilter(PART_AERO_REVISION));
            return BOMLineHolderHelper.findFirst(expandedRfGenericBom, PART_AERO_REVISION);
        } catch (NotFoundException e) {
            log.trace("No RF Generic previously loaded in the Generic", e);
            return null;
        }
    }
}
