package com.capgemini.reports.definition.r15r16r17reports.r15r17reports.r17report;

import com.capgemini.framework.teamcenter.authent.TcSession;
import com.capgemini.framework.teamcenter.exceptions.KurtException;
import com.capgemini.framework.teamcenter.queries.saved.modelobject.ItemRevisionQuery;
import com.capgemini.reports.definition.r15r16r17reports.r15r17reports.AbstractDataReportPreparatorR15R17;
import com.capgemini.reports.exceptions.InvalidUserInputException;
import com.capgemini.reports.execution.strategies.IExecutionStrategy;
import com.capgemini.reports.printing.PrintParameters;
import com.teamcenter.soa.client.model.strong.ItemRevision;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * Prepares the Data for the R17 report.
 */
public class DataReportPreparatorR17 extends AbstractDataReportPreparatorR15R17<ExecutionR17> {
    private static final long serialVersionUID = -6169580009749438941L;
    private static final Logger LOGGER = LoggerFactory.getLogger(DataReportPreparatorR17.class);

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

        session.setObjectPropPolicy(report.getFullPolicy());

        List<ItemRevision> revisionsSnecmaObject = new ItemRevisionQuery(session).searchID(report.getItemId()).findAll();
        if (revisionsSnecmaObject.isEmpty()) {
            throw new InvalidUserInputException("Unabled to retrieve the list of revisons of the Part " + report.getItemId());
        }

        // Retrieve topItemRev
        ItemRevision topItemRevision = retrieveTopItemRevision(report.getItemRevision(), revisionsSnecmaObject);

        // Retrieve all common data
        doPrepareCommonDataForAllReports(session, topItemRevision, revisionsSnecmaObject, report);

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

        LOGGER.debug("PrepareData ended on: {}", report.getReportIdentifier().getReportTitle());
        return printParameters;
    }
}
