package oracle.adfdi.demo.cf.model.errorhandler;

import oracle.adf.model.RegionBinding;
import oracle.adf.model.binding.DCErrorMessage;

import java.util.ResourceBundle;

public class MyDCErrorMessage implements DCErrorMessage {
    RegionBinding regionBinding;
    Exception exception;

    public MyDCErrorMessage(RegionBinding rb, Exception ex) {
        super();
        this.regionBinding = rb;
        this.exception = ex;
    }

    public String getText() {
        return "Message String";
    }

    public String getHTMLText() {
        String formattedError = null;

        /* Gets the display label of attribute from the resource bundle and return the error by appending the exception message*/
        if (exception instanceof oracle.jbo.AttrValException) {
            System.out.println("instance of AttrValException");
            oracle.jbo.AttrValException ave = (oracle.jbo.AttrValException)exception;

            ResourceBundle bundle = ResourceBundle.getBundle("oracle.adfdi.demo.cf.model.ModelBundle");

            formattedError =
                    "<font color=\"red\">" + ave.getLocalizedMessage() + "</font><br/>" + "<b>Cause:</b> You provoked a " +
                    ave.getClass() + " in the " + regionBinding.getName() + "<br/>" + "<b>Action:</b> Avoid doing " +
                    ave.getClass() + " in the " + regionBinding.getName() + "<hr/>";
            return formattedError;

        }

        /*Formats the error message with html tags and return the error message with cause and action */
        if (exception instanceof oracle.jbo.JboException) {
            System.out.println("instance of JboException");
            oracle.jbo.JboException jboe = (oracle.jbo.JboException)exception;

            formattedError =
                    "<font color=\"red\">" + jboe.getLocalizedMessage() + "</font><br/>" + "<b>Cause:</b> You provoked a " +
                    jboe.getClass() + " in the " + regionBinding.getName() + "<br/>" + "<b>Action:</b> Avoid doing " +
                    jboe.getClass() + " in the " + regionBinding.getName() + "<hr/>";
            return formattedError;
        }

        /*In case of SQL Exception, returns error message with the error code*/
        if (exception instanceof java.sql.SQLException) {
            System.out.println("instance of SQLException");
            java.sql.SQLException sqle = (java.sql.SQLException)exception;

            return "SQL Exception with error code: " + sqle.getErrorCode() + " is thrown";
        }
        
        return exception.getLocalizedMessage();
    }
}
