package com.capgemini.reports.builder;

import com.capgemini.framework.teamcenter.authent.TcSession;
import com.capgemini.framework.teamcenter.exceptions.NoTeamcenterConnectionException;
import com.capgemini.framework.teamcenter.queries.saved.modelobject.ItemRevisionQuery;
import com.capgemini.reports.database.javabean.enumeration.ReportCriteriaEnum;
import com.capgemini.reports.definition.r19report.ExecutionR19;
import com.capgemini.reports.exceptions.InsufficientParametersException;
import com.google.common.base.Joiner;
import com.teamcenter.soa.client.model.strong.ItemRevision;

import java.util.List;
import java.util.Map;

/**
 * Builds a R19 Report from document ID, Document revision, and document type.
 */
public class R19Builder implements ReportBuilder {

    @Override
    public ExecutionR19 build(Map<ReportCriteriaEnum, String> data) throws InsufficientParametersException {
        // Get the request raw data
        String documentId = data.get(ReportCriteriaEnum.DOCUMENT_ID);
        String documentRev = data.get(ReportCriteriaEnum.DOCUMENT_REVISION);
        String documentType = data.get(ReportCriteriaEnum.TYPE_OBJET);

        // Check presence of all required args
        if (documentId == null || documentRev == null || documentType == null) {
            String dataStr = Joiner.on('|').withKeyValueSeparator("=").useForNull("null").join(data);
            throw new InsufficientParametersException("Missing parameter for R19 launch. Obtained: " + dataStr);
        }

        try (TcSession session = new TcSession()) {
            session.login();
            ItemRevisionQuery query = new ItemRevisionQuery(session);
            query.searchType(documentType);
            query.searchIDAndRevision(documentId, documentRev);
            List<ItemRevision> results = query.findAll();
            ItemRevision doc = results.get(0);
            return new ExecutionR19(documentId, documentRev, documentType, doc.getUid());
        } catch (NoTeamcenterConnectionException e) {
            String dataStr = Joiner.on('|').withKeyValueSeparator("=").useForNull("null").join(data);
            throw new InsufficientParametersException("Unable to retrieve document UID from id+rev. Request : " + dataStr, e);
        }
    }
}
