package com.capgemini.reports.definition.r01report;

import com.capgemini.framework.teamcenter.authent.TcSession;
import com.capgemini.framework.teamcenter.exceptions.EmptyNomenclatureException;
import com.capgemini.framework.teamcenter.exceptions.KurtException;
import com.capgemini.framework.teamcenter.object.pom.workspace.bom.TcBomObject;
import com.capgemini.framework.teamcenter.object.pom.workspace.bom.TcBomObjectFactory;
import com.capgemini.framework.teamcenter.object.pom.workspace.bom.TcRevisionRule;
import com.capgemini.framework.teamcenter.object.pom.workspace.bom.TcRevisionRuleProperties;
import com.capgemini.framework.teamcenter.object.pom.workspace.bom.product.TcProduct;
import com.capgemini.framework.teamcenter.object.pom.workspace.bom.product.TcProductRevision;
import com.capgemini.framework.teamcenter.object.runtime.TcBomWindow;
import com.capgemini.framework.teamcenter.object.runtime.TcBomWindowConfiguration;
import com.capgemini.framework.teamcenter.object.runtime.TcRevisionRulesConfiguration;
import com.capgemini.reports.bomlineholder.BOMLineHolder;
import com.capgemini.reports.bomlineholder.BOMLineHolderFactory;
import com.capgemini.reports.bomlineholder.processor.DefaultAltOrDetBehaviour;
import com.capgemini.reports.definition.r01report.visitors.R01Visitor;
import com.capgemini.reports.exceptions.InvalidUserInputException;
import com.capgemini.reports.exceptions.UserInputErrorEnum;
import com.capgemini.reports.execution.IDataReportPreparator;
import com.capgemini.reports.execution.strategies.IExecutionStrategy;
import com.capgemini.reports.filter.AllIsGoodFilter;
import com.capgemini.reports.printing.PrintParameters;
import com.capgemini.reports.reports.parameters.EffectivityDate;
import com.capgemini.reports.reports.parameters.MonoMulti;
import com.capgemini.reports.teamcenter.resolution.structureservice.IStructureServiceCaller;
import com.capgemini.reports.teamcenter.resolution.structureservice.MultiStructureServiceCaller;
import com.capgemini.reports.teamcenter.resolution.structureservice.TripleStructureServiceCaller;
import com.teamcenter.soa.client.model.ModelObject;
import com.teamcenter.soa.client.model.strong.Form;
import com.teamcenter.soa.client.model.strong.PSBOMView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * This class will allow to prepare data and findAll back data for making report R01.
 */
class DataReportPreparatorR01 implements IDataReportPreparator<ExecutionR01> {
    private static final long serialVersionUID = -1029419855928264125L;
    private static final Logger LOGGER = LoggerFactory.getLogger(DataReportPreparatorR01.class);

    private static final AllIsGoodFilter ACCEPT_ALL = new AllIsGoodFilter();

    @Override
    public String print(TcSession session, ExecutionR01 execution, IExecutionStrategy executionStrategy) throws KurtException {
        PrintParameters printParameters = prepareData(session, execution);
        executionStrategy.print(printParameters, execution);
        return executionStrategy.getReportFileName(execution) + printParameters.getOuputFileExtension();
    }

    private PrintParameters prepareData(final TcSession session, final ExecutionR01 report) throws KurtException {
        LOGGER.debug("PrepareData started on: {}", report.getReportIdentifier().getReportTitle());

        TcBomObject topLineObject= new TcBomObjectFactory(session, report.getGeneric().getItem(session)).create();
        TcProduct productObject = new TcProduct(session, report.getProductUnit().getProduct(session));
        TcProductRevision productObjectRevision = productObject.revisions().get(0);
        int unit = report.getProductUnit().getUnit();
        EffectivityDate effectivityDate = report.getEffectivityDate();

        TcRevisionRuleProperties revisionRuleProperties = new TcRevisionRuleProperties(productObject, unit, effectivityDate.isNow() ? null : effectivityDate.getDateTime());
        TcRevisionRule revisionRule = session.findRevRule(report.getRevisionRule());
        TcRevisionRulesConfiguration revRulesConfiguration = new TcRevisionRulesConfiguration(revisionRule, revisionRuleProperties);

        IStructureServiceCaller service;
        if (MonoMulti.MONO.equals(report.getMonoMulti())) {
            service = new TripleStructureServiceCaller(session);
        } else {
            service = new MultiStructureServiceCaller(session);
        }

        TcBomWindowConfiguration tcBomWindowConfiguration ;
        if (report.isSuperModelBOM()) {
            PSBOMView modelBom = productObjectRevision.bomViewRev();
            tcBomWindowConfiguration = new TcBomWindowConfiguration (topLineObject,modelBom,revRulesConfiguration);
        } else {
            tcBomWindowConfiguration = new TcBomWindowConfiguration(topLineObject, revRulesConfiguration);
        }

        try (TcBomWindow bomWindow = session.createBomWindow(tcBomWindowConfiguration)) {
            session.setObjectPropPolicy(report.getFullPolicy());
            BOMLineHolder unbuiltTopLine = service.resolve(bomWindow.topLine(), ACCEPT_ALL);
            List<Form> itemRevMaster = unbuiltTopLine.getAllItemRevMasters();
            session.loadProperties(itemRevMaster.toArray(new ModelObject[itemRevMaster.size()]));

            BOMLineHolderFactory.buildTopBom(session, unbuiltTopLine, ACCEPT_ALL);
            DefaultAltOrDetBehaviour<Object, Object> aBOMLineHolderProcessor = new DefaultAltOrDetBehaviour<>(session, effectivityDate.isNow() ? null : effectivityDate.getDateTime());
            unbuiltTopLine.process(aBOMLineHolderProcessor);
            unbuiltTopLine.freeze();

            R01Visitor visitor = new R01Visitor();
            PrintParameters printParameters = visitor.makeMasterTemplate(report, unbuiltTopLine);
            visitor.constructDataMaps(session, printParameters, unbuiltTopLine);

            LOGGER.debug("PrepareData ended on: {}", report.getReportIdentifier().getReportTitle());
            return printParameters;
        } catch (EmptyNomenclatureException e) {
            switch (report.getGeneric().getType()) {
                case GENERIC:
                    throw new InvalidUserInputException(UserInputErrorEnum.NO_DATA_COULD_BE_EXTRACTED_FOR_GENERIC_PRODUCT_AND_UNIT, e);
                case GENERIC_ASSEMB:
                    throw new InvalidUserInputException(UserInputErrorEnum.NO_DATA_COULD_BE_EXTRACTED_FOR_GENERIC_ASSEMB_PRODUCT_AND_UNIT, e);
                default:
                    throw new KurtException("The TC Nomenclature Resolution returned null", e);
            }
        }
    }
}
