/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.products.ov.commons.dto;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MixingError {

    private static final Logger logger = LoggerFactory.getLogger(MixingError.class);

    public static final int MAX_RETRIES = 5;

    private String errorMessage;

    private String errorClass;

    private String stackTrace;

    private int retriesLeft;

    MixingError(Throwable error) {
        update(error);
        this.retriesLeft = MAX_RETRIES;
    }

    MixingError(String errorMessage, String errorClass, String stackTrace, int retriesLeft) {
        this.errorMessage = errorMessage;
        this.errorClass = errorClass;
        this.stackTrace = stackTrace;
        this.retriesLeft = retriesLeft;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public String getErrorClass() {
        return errorClass;
    }

    public String getStackTrace() {
        return stackTrace;
    }

    public int getRetriesLeft() {
        return retriesLeft;
    }

    /**
     * Updates the error with a new error condition.
     *
     * @param error
     *            the error to update this error with.
     */
    public void update(Throwable error) {
        // New error, so one less retry left.
        retriesLeft--;
        // Update the internal error data.
        errorMessage = error.getMessage();
        errorClass = error.getClass().getName();
        try (StringWriter sw = new StringWriter()) {
            error.printStackTrace(new PrintWriter(sw));
            stackTrace = sw.toString();
        } catch (IOException e) {
            stackTrace = "Stack trace not available";
            logger.debug(stackTrace, e);
        }
    }
}
