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

import com.capgemini.framework.teamcenter.authent.TcSession;
import com.capgemini.framework.teamcenter.queries.saved.modelobject.ItemQuery;
import com.capgemini.reports.exceptions.InvalidUserInputException;
import com.capgemini.reports.exceptions.UserInputErrorEnum;
import com.capgemini.reports.reports.parameters.Generics;
import com.capgemini.reports.reports.parameters.IChecker;
import com.teamcenter.soa.client.model.strong.Item;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * This class checks if a Generics (which represents a Generic and/or GenericAssemb) exists within the TC database.
 */
@Slf4j
public class GenericExistenceChecker implements IChecker {

    protected final Generics generics;

    public GenericExistenceChecker(final Generics generics) {
        this.generics = generics;
    }

    @Override
    public void check(final TcSession session) throws InvalidUserInputException {
        switch (generics.getType()) {
            case GENERIC:
                genericExists(session);
                break;
            case GENERIC_ASSEMB:
                genericAssembExists(session);
                break;
            case ONLY_PRODUCT:
                break;
            default:
                log.error("Unsupported Enum value");
                break;
        }
    }

    protected void genericExists(final TcSession session) throws InvalidUserInputException {
        List<Item> list = new ItemQuery(session).searchID(generics.getGeneric()).searchGeneric().findAll();
        if (list == null || list.isEmpty()) {
            throw new InvalidUserInputException(getTechnicalErrorMsg());
        }
    }

    protected UserInputErrorEnum getTechnicalErrorMsg() {
        return UserInputErrorEnum.GENERIC_DOES_NOT_EXIST;
    }

    private void genericAssembExists(final TcSession session) throws InvalidUserInputException {
        List<Item> list = new ItemQuery(session).searchID(generics.getGenericAssemb()).searchGenericAssemb().findAll();
        if (list == null || list.isEmpty()) {
            throw new InvalidUserInputException(getAssemblyErrorMsg());
        }
    }

    private UserInputErrorEnum getAssemblyErrorMsg() {
        return UserInputErrorEnum.GENERIC_ASSEMB_DOES_NOT_EXIST;
    }
}
