package com.capgemini.reports.definition.r26report;

import com.capgemini.framework.teamcenter.authent.TcSession;
import com.capgemini.framework.teamcenter.exceptions.KurtException;
import com.capgemini.framework.teamcenter.object.pom.workspace.bom.TcRevisionRule;
import com.capgemini.reports.exceptions.InvalidUserInputException;
import com.capgemini.reports.exceptions.UserInputErrorEnum;
import com.capgemini.reports.teamcenter.queries.TypeQuery;
import com.teamcenter.soa.client.model.strong.RevisionRule;
import lombok.Getter;

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

/**
 * Manager for Revision Rule for making report R26.
 */
@Getter
class RevisionRuleManager {

    private RevisionRule revisionRule;
    private String revisionRuleName;
    private TcRevisionRule tcRevisionRule;

    RevisionRuleManager(TcSession session, RevisionRule reportRevRule, String newRevRuleName) throws InvalidUserInputException {
        try {
            session.cloneRevisionRule(reportRevRule, newRevRuleName);
        }
        catch (Exception e) {
            throw new InvalidUserInputException(UserInputErrorEnum.UNABLE_TO_USE_REVISION_RULE);
        }

        List<RevisionRule> list = TypeQuery.getRevisionRule(session, newRevRuleName);

        if (list.isEmpty()) {
            throw new InvalidUserInputException(UserInputErrorEnum.UNABLE_TO_USE_REVISION_RULE);
        }
        else {
            revisionRule = list.get(0);
            tcRevisionRule = new TcRevisionRule(session, revisionRule);
            session.loadProperties(revisionRule, "object_name");
            revisionRuleName = revisionRule.get_object_name();
        }
    }

    /**
     * Mise à jour des valeurs Article et Produit de la règle de révision du rapport R26.
     */
    void setProductUnitRevisionRuleProperties(String productUid, int unit) {
        Map<String, Object> map = new HashMap<>();
        map.put("rule_unit", String.valueOf(unit));
        map.put("rule_end_item", productUid);

        tcRevisionRule.setProperties(map);
    }
}
