package com.capgemini.reports.reports.parameters.checker;

import com.capgemini.framework.teamcenter.authent.TcSession;
import com.capgemini.reports.exceptions.InvalidUserInputException;
import com.capgemini.reports.exceptions.NotFoundException;
import com.capgemini.reports.exceptions.UserInputErrorEnum;
import com.capgemini.reports.reports.parameters.IChecker;
import com.capgemini.reports.teamcenter.queries.DirectQuery;
import com.teamcenter.soa.client.model.ModelObject;
import com.teamcenter.soa.client.model.strong.Item;
import com.teamcenter.soa.client.model.strong.ItemRevision;

import java.util.regex.Pattern;


/** This class checks if a ModelObject exists by looking for its uid in Teamcenter. */
public class ModelObjectChecker implements IChecker {

    private final String[] typePatterns;
    private final String objectUID;

    /**
     * Constructs a checker that verifies if the type of the ModelObject whose UID is provided matches any of the type filters.<br>
     * Note: the provided types maybe Item Master or Item Revision Types.<br>
     * Note2: At least one filter element must be provided.
     * 
     * @param objectUID String UID of the ModelObject
     * @param typeFilters the allowed types. Each must be an {@link Item}'s Type or {@link ItemRevision}'s type (i.e. 'DocNorm' or 'DocDrawing Revision')...
     */
    public ModelObjectChecker(final String objectUID, final String... typeFilters) {
        this.objectUID = objectUID;
        this.typePatterns = new String[typeFilters.length];

        for (int num = 0; num < typeFilters.length; num++) {
            this.typePatterns[num] = ".*" + typeFilters[num] + ".*";
        }
    }

    @Override
    public void check(final TcSession session) throws InvalidUserInputException {
        if (typePatterns.length == 0) {
            throw new InvalidUserInputException("No Type pattern was specified"); // Should never happen: one must not build a checker without at least one filter element
        }

        ModelObject modelObject;
        try {
            modelObject = new DirectQuery<>(session).searchByUID(objectUID);
        }
        catch (NotFoundException e) {
            throw new InvalidUserInputException(UserInputErrorEnum.OBJECT_DOES_NOT_EXIST, e);
        }

        String actualType = modelObject.getTypeObject().getName();

        for (String type : typePatterns) {
            if (Pattern.matches(type, actualType)) {
                return; // Type is ok
            }
        }
        // If we findAll here type is not authorised
        throw new InvalidUserInputException(UserInputErrorEnum.TYPE_DOCUMENT_SELECTED_NOT_AUTHORIZED);
    }

}
