package com.foreverwin.mesnac.dataimport.util;

import com.sap.me.frame.BasicBOBeanException;
import com.sap.me.frame.Utils;
import com.sap.me.frame.domain.BusinessException;
import com.sap.me.frame.mapping.ServiceContext;
import com.sap.me.frame.utils.I18nUtility;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class MessageHandler
{
  public static String handleExceptionMessage(BusinessException ex)
  {
    String text = null;
    if (ex.getCause() instanceof BasicBOBeanException) {
      text = ex.getLocalizedMessage();
    }
    if (Utils.isBlank(text)) {
      text = I18nUtility.getMessageForException(ex);
      text = appendErrorCode(text, ex.getErrorCode());
    }
    return text;
  }


  public static String handleMessage(String messageKey, Map<String, Object> messageParams, MsgType type)
  {
    MsgType msgType = type;
    if (msgType == null) {
      msgType = MsgType.INFO;
    }
    HashMap params = null;
    if (messageParams != null) {
      if (messageParams instanceof HashMap)
        params = (HashMap)messageParams;
      else {
        params = new HashMap(messageParams);
      }
    }

    String text = null;
    String typeMsg = "ERROR_MESSAGE";
    if (!(MsgType.ERROR.equals(msgType))) {
      typeMsg = "INFORMATION_MESSAGE";
    }
    text = I18nUtility.i18nizeMessageText(messageKey, params, typeMsg);
    if ((!(Utils.isBlank(text))) && (MsgType.ERROR.equals(type)) && 
      (messageKey.endsWith(".simple"))) {
      String errorCode = messageKey.split("[.]+")[0];
      text = appendErrorCode(text, errorCode);
    }

    if (Utils.isBlank(text)) {
      text = messageKey;
    }
    return text;
  }





  public static Locale getUserPreferedLocale()
  {
    String loc = (String)ServiceContext.instance().getProperty("LOCALE");
    return new Locale(loc);
  }

  private static String appendErrorCode(String message, int errorCode) {
    String errorCodeString = null;
    try {
      errorCodeString = String.valueOf(errorCode);
    } catch (Exception ex) {
      return message;
    }
    return appendErrorCode(message, errorCodeString);
  }

  private static String appendErrorCode(String message, String errorCode) {
    StringBuffer result = new StringBuffer(message);
    String errorLabel = I18nUtility.i18nizeMessageText("error.label", null, "ERROR_MESSAGE");
    if (!(Utils.isBlank(errorLabel))) {
      result.append(" (").append(errorLabel).append(' ').append(errorCode).append(')');
    }
    return result.toString(); }

  public static enum MsgType {
    ERROR, INFO;
  }
}