package com.capgemini.framework.teamcenter;

import com.teamcenter.soa.client.model.ErrorStack;
import com.teamcenter.soa.client.model.ErrorValue;
import com.teamcenter.soa.client.model.ModelObject;
import com.teamcenter.soa.client.model.ServiceData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ServiceDataHelper {
    private static final Logger LOGGER = LoggerFactory.getLogger(ServiceDataHelper.class);

    private ServiceDataHelper() {
        // utility
    }

    /**
     * Check if the service data has errors.
     *
     * @param serviceData
     *          ServiceData instance
     * @return True when no error occurs, else return false
     */
    public static boolean hasErrors(final ServiceData serviceData) {
        return serviceData.sizeOfPartialErrors() > 0;
    }

    /**
     * Log potential errors throw from a service data.
     *
     * @param serviceData
     *          ServiceData instance
     * @return True when no error occurs, else return false
     */
    public static void displayErrors(final ServiceData serviceData) {
        LOGGER.debug("Error count: {}", serviceData.sizeOfPartialErrors());
        for (int i = 0; i < serviceData.sizeOfPartialErrors(); i++) {
            displayError(serviceData.getPartialError(i));
        }
    }

    /**
     * Display error stack from service data.
     *
     * @param errorStack Stack error from service
     */
    private static void displayError(final ErrorStack errorStack) {
        LOGGER.debug("Error stack from client: clientIndex = {}, clientId = {}", errorStack.getClientIndex(),
                errorStack.getClientId());
        ModelObject associatedObject = errorStack.getAssociatedObject();
        StringBuilder theLogBuilder = new StringBuilder();
        if (associatedObject != null) {
            theLogBuilder.append("object UID = [").append(associatedObject.getUid()).append("]");
        } else {
            theLogBuilder.append("associatedObject = [null]");
        }
        LOGGER.debug("        " + theLogBuilder.toString());

        ErrorValue[] errorValues = errorStack.getErrorValues();
        if (errorValues == null) {
            return;
        }
        for (ErrorValue currentErrorVal : errorValues) {
            if (currentErrorVal != null) {
                LOGGER.debug("        errVal :");
                LOGGER.debug("             code  = {}", currentErrorVal.getCode());
                LOGGER.debug("             level = {}", currentErrorVal.getLevel());
                LOGGER.debug("             msg   = {}", currentErrorVal.getMessage());
            }
        }
    }
}