/*
 * Copyright (c) eHealth
 */
package be.ehealth.business.mycarenetcommons.helper;

import java.util.List;

import org.junit.Assert;

import be.fgov.ehealth.messageservices.core.v1.RetrieveTransactionResponse;
import be.fgov.ehealth.standards.kmehr.cd.v1.CDERRORMYCARENET;
import be.fgov.ehealth.standards.kmehr.schema.v1.ErrorMyCarenetType;


/**
 * manage the error list of RetrieveTransactionResponse.
 * 
 * @author EH058
 * 
 * @since
 * 
 */
public final class ErrorMyCarenetTypeManagement {

    /**
     * 
     */
    private ErrorMyCarenetTypeManagement() {
        super();
    }

    /**
     * get the errors list from the response
     * 
     * @param response
     * @return errors list
     */
    public static List<ErrorMyCarenetType> getError(RetrieveTransactionResponse response) {
        return response.getAcknowledge().getErrors();
    }

    /**
     * check if the errors list contains one or more codes.
     * 
     * @param errors
     * @param codes
     */
    public static void isErrorsContainSpecificCode(List<ErrorMyCarenetType> errors, String... codes) {
        boolean found, failed = false;
        StringBuffer returnValue = new StringBuffer();
        for (String code : codes) {
            found = false;
            for (int i = 0; i < errors.size(); i++) {
                ErrorMyCarenetType error = errors.get(i);
                if (code.equals(error.getCds().get(0).getValue())) {
                    returnValue.append("code " + code + " found in error list \n");
                    errors.remove(error);
                    found = true;
                    i--;
                }
            }
            if (!found) {
                returnValue.append("code " + code + " expected but not found in errors list \n");
                failed = true;
            }
        }
        for (ErrorMyCarenetType error : errors) {
            returnValue.append("code " + error.getCds().get(0).getValue() + " found in errors list but not expected (" + error.getDescription() + ") \n");
            failed = true;
        }
        if (failed) {
            Assert.fail(returnValue.toString());
        }

    }

    public static String printError(ErrorMyCarenetType error) {
        StringBuffer returnValue = new StringBuffer("errors codes = ");
        for (CDERRORMYCARENET cd : error.getCds()) {
            returnValue.append(cd.getValue() + " ");
        }
        returnValue.append("Description : " + error.getDescription() + " ");
        returnValue.append("url : " + error.getUrl());
        return returnValue.toString();
    }

    public static String printErrors(List<ErrorMyCarenetType> errors) {
        StringBuffer returnValue = new StringBuffer();
        for (ErrorMyCarenetType error : errors) {
            returnValue.append(printError(error));
        }
        return returnValue.toString();
    }
}
