package com.capgemini.framework.teamcenter.relations;

import com.capgemini.framework.teamcenter.TeamcenterObjectTypes;
import com.capgemini.framework.teamcenter.authent.TcSession;
import com.capgemini.framework.teamcenter.exceptions.FailedRelationshipActionException;
import com.capgemini.framework.teamcenter.exceptions.MalformedDataSetException;
import com.capgemini.framework.teamcenter.exceptions.NoTeamcenterConnectionException;
import com.capgemini.framework.teamcenter.files.DatasetPreparator;
import com.capgemini.framework.teamcenter.files.FileManagement.FileType;
import com.capgemini.framework.teamcenter.queries.saved.modelobject.ItemQuery;
import com.teamcenter.schemas.soa._2006_03.exceptions.InvalidCredentialsException;
import com.teamcenter.services.loose.core._2006_03.FileManagement.GetDatasetWriteTicketsInputData;
import com.teamcenter.soa.client.model.ModelObject;
import com.teamcenter.soa.client.model.strong.Item;
import junit.framework.Assert;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.File;
import java.util.NoSuchElementException;

public class RelationshipManagerTest {

    private static final String DATASET_NAME = "TestDataset";
    private static final String PART_ID = "002711";
    private static final String FILE_NAME = "jasperPdfPrinterTest.pdf";
    private static final String FOLDER = "src/test/resources/";

    private final TcSession session = new TcSession();
    private ModelObject dataset;

    @Before
    public void makeDataset() throws MalformedDataSetException, InvalidCredentialsException, NoTeamcenterConnectionException {
        session.login();
        DatasetPreparator datapreparator = new DatasetPreparator(session, DATASET_NAME, "For Kurt Unit testing");
        File theFile = new File(FOLDER + FILE_NAME);
        if (!theFile.exists() || theFile.isDirectory()) {
            throw new NoSuchElementException("Missing test file " + FOLDER + FILE_NAME); // This is the failure of the test-class, not of the class being tested
        }
        datapreparator.addFile(theFile, FileType.FICHE_ARTICLE);
        GetDatasetWriteTicketsInputData datasetTicket = datapreparator.prepare();
        dataset = datasetTicket.dataset;
    }

    @Test
    public void createDeleteTest() throws InvalidCredentialsException, FailedRelationshipActionException, NoTeamcenterConnectionException {
        Item part = new ItemQuery(session).searchID(PART_ID).findAll().get(0);

        // Create the link
        Assert.assertNotNull(session.createRelation(part, dataset, TeamcenterObjectTypes.IMAN_REFERENCE));
        session.deleteRelations(part, dataset, TeamcenterObjectTypes.IMAN_REFERENCE);
    }

    /**
     * Destroy the dataset.
     */
    @After
    public void cleanup() {
        session.deleteObjects(dataset);
        session.close();
    }
}
