package com.jscape.util.event;

import com.jscape.util.Assert;

/**
 * @author Alex Usun
 */
public abstract class AbstractRequest
        extends AbstractEvent {

    /**
     * Error message.
     */
    protected String errorMessage;
    /**
     * Error.
     */
    protected Throwable error;

    /**
     * @param context EventContext instance
     */
    protected AbstractRequest(EventContext context) {
        super(context);
    }

    /**
     * @param value value
     */
    public void setError(Throwable value) {
        setError(null, value);
    }

    /**
     * @param errorMessage errorMessage
     * @param error        Throwable instance
     */
    public void setError(String errorMessage, Throwable error) {
        this.errorMessage = errorMessage;

        Assert.notNull(error);
        this.error = error;

        setHandled();
    }

    /**
     * @throws RequestException requestException
     */
    protected void assertNoErrors()
            throws RequestException {
        if (this.error == null) {
            return;
        }

        if (this.errorMessage != null) {
            throw new RequestException(this.errorMessage, this.error);
        } else {
            throw new RequestException(this.error);
        }
    }

    /**
     * @throws RequestNotHandledException requestNotHandledException
     */
    protected void assertHandledExplicitly()
            throws RequestNotHandledException {
        if (!this.handled) {
            throw new RequestNotHandledException();
        }
    }

    /**
     * RequestException class.
     */
    public static class RequestException
            extends Exception {

        /** */
        public RequestException() {
        }

        /**
         * @param message message
         */
        public RequestException(String message) {
            super(message);
        }

        /**
         * @param message message
         * @param cause   cause
         */
        public RequestException(String message, Throwable cause) {
            super(message, cause);
        }

        /**
         * @param cause cause
         */
        public RequestException(Throwable cause) {
            super(cause);
        }
    }

    /**
     * RequestNotHandledException class.
     */
    public static class RequestNotHandledException
            extends RequestException {
    }
}
