package com.capgemini.framework.teamcenter.queries.saved.modelobject;

import com.capgemini.framework.teamcenter.TeamcenterObjectTypes;
import com.capgemini.framework.teamcenter.authent.TcSession;
import com.capgemini.framework.teamcenter.queries.saved.AbstractReplicatedQuery;
import com.teamcenter.soa.client.model.strong.ImanRelation;

import java.util.List;

/**
 * A Tc Query that can be used to search exisitng relations between a primary and a secondary object.
 */
public class IMANRelationQuery {
    private final TcSession session;

    /**
     * Creates an instance that is able to perform queries.
     *
     * @param session an active session
     */
    public IMANRelationQuery(final TcSession session) {
        this.session = session;
    }

    /**
     * Returns all {@link ImanRelation} referenced datasets (in a {@link List}) of an item.
     *
     * @param itemId      the Item's ID
     * @param datasetName the dataset name
     * @return a List of ImanRelation
     */
    public List<ImanRelation> find(final String itemId, final String datasetName) {
        TheInternalRelationQuery query = new TheInternalRelationQuery(session);
        return query.find(itemId, datasetName);
    }

    private static final class TheInternalRelationQuery extends AbstractReplicatedQuery<ImanRelation, TheInternalRelationQuery> {
        private static final String QUERY_SUFFIX = "Relationship";

        private static final String KEY_DATASET_NAME = REPCOL_PREFIX + "dataset_name";
        private static final String KEY_ITEM_ID = REPCOL_PREFIX + "item_id";
        private static final String KEY_RELATIONSHIP = REPCOL_PREFIX + "relationship";

        protected TheInternalRelationQuery(final TcSession session) {
            super(session, QUERY_SUFFIX);
        }

        /**
         * Finds an {@link ImanRelation} between an item and a dataset.
         *
         * @param itemId      the ID of the Item
         * @param datasetName the name of the dataset
         * @return a {@link List} of all the {@link ImanRelation}s found
         */
        public List<ImanRelation> find(final String itemId, final String datasetName) {
            addParam(KEY_RELATIONSHIP, TeamcenterObjectTypes.IMAN_REFERENCE);
            addParam(KEY_ITEM_ID, itemId);
            addParam(KEY_DATASET_NAME, datasetName);
            return this.findAll();
        }

        @Override
        protected TheInternalRelationQuery selfCast() {
            return this;
        }

    }

}
