package com.capgemini.reports.definition.r11report;

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.runtime.TcBomWindow;
import com.capgemini.framework.teamcenter.object.runtime.TcBomWindowConfiguration;
import com.capgemini.framework.teamcenter.object.runtime.TcRevisionRulesConfiguration;
import com.capgemini.framework.teamcenter.object.types.SnecmaObjectTypes;
import com.capgemini.reports.bomlineholder.BOMLineHolder;
import com.capgemini.reports.bomlineholder.BOMLineHolderFactory;
import com.capgemini.reports.definition.r11report.data.extractor.FilterByTypeObject;
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.Generics;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;


/**
 * Class which prepare data for the reports.
 */
public class DataReportPreparatorR11 implements IDataReportPreparator<ExecutionR11> {
    private static final long serialVersionUID = 6949217671922185431L;
    private static final Logger LOGGER = LoggerFactory.getLogger(DataReportPreparatorR11.class);

    @Override
    public String print(TcSession session, ExecutionR11 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 ExecutionR11 report) throws KurtException {
        LOGGER.debug("PrepareData started on: {}", report.getReportIdentifier().getReportTitle());

        // Setup the policy
        session.setObjectPropPolicy(report.getFullPolicy());

        Generics generic = report.getGeneric();
        TcBomObject topLineObject = new TcBomObjectFactory(session, report.getGeneric().getItem(session)).create();
        TcProduct productObject = new TcProduct(session, generic.getProductUnit().getProduct(session));
        int unit = generic.getProductUnit().getUnit();
        EffectivityDate effectivityDate = report.getEffectivity();

        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);
        }

        try (TcBomWindow bomWindow = session.createBomWindow(new TcBomWindowConfiguration(topLineObject, revRulesConfiguration))) {
            session.setObjectPropPolicy(report.getFullPolicy());

            BOMLineHolder unbuiltTopLine = service.resolve(bomWindow.topLine(), new AllIsGoodFilter());
            List<Form> itemRevMaster = unbuiltTopLine.getAllItemRevMasters();
            session.loadProperties(itemRevMaster.toArray(new ModelObject[itemRevMaster.size()]));

            BOMLineHolderFactory.buildTopBom(session, unbuiltTopLine, new FilterByTypeObject(SnecmaObjectTypes.ALTERNATE_REVISION,
                    SnecmaObjectTypes.DET_REVISION, SnecmaObjectTypes.RF_PART_REVISION, SnecmaObjectTypes.PART_AERO_REVISION,
                    SnecmaObjectTypes.PART_MAT_REVISION, SnecmaObjectTypes.PART_NO_AERO_REVISION, SnecmaObjectTypes.GENERIC_REVISION,
                    SnecmaObjectTypes.RF_GENERIC_REVISION, SnecmaObjectTypes.STANDARD_REVISION, SnecmaObjectTypes.MOCKUP_REVISION,
                    SnecmaObjectTypes.RF_ADMIN_AG_REVISION, SnecmaObjectTypes.RF_ADMIN_AP_REVISION, SnecmaObjectTypes.RF_ADMIN_REVISION));


            R11Printer printer = new R11Printer();
            PrintParameters printParameters = printer.makeMasterTemplate(report, unbuiltTopLine);
            printer.constructDataMaps(session, printParameters, unbuiltTopLine);

            return printParameters;
        } catch (EmptyNomenclatureException e) {
            switch (generic.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);
            }
        }
    }
}
