package com.airlock.iam.base.misc.message;

import com.airlock.iam.elog.api.ELogger;
import com.airlock.iam.elog.api.ELoggerFactory;
import com.airlock.iam.elog.api.LogTypes;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.text.Format;
import java.util.Locale;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.FormatFactory;

public final class GrowableFormatFactory implements FormatFactory {
   public static final String LEFT_ALIGNED_FORMAT_IDENTIFIER = "left";
   public static final String RIGHT_ALIGNED_FORMAT_IDENTIFIER = "right";
   public static final String MID_ABBREV_FORMAT_IDENTIFIER = "mid";
   private static final ELogger LOG = ELoggerFactory.getLogger(GrowableFormatFactory.class);
   private static final GrowableFormatFactory INSTANCE = new GrowableFormatFactory();

   public static GrowableFormatFactory getInstance() {
      return INSTANCE;
   }

   public Format getFormat(String name, String arguments, Locale locale) {
      try {
         if ("left".equals(name)) {
            return arguments != null && !"".equals(arguments) ? new GrowableFormat(Integer.parseInt(arguments), 0) : new GrowableFormat(1, 0);
         }

         if ("right".equals(name)) {
            return arguments != null && !"".equals(arguments) ? new GrowableFormat(0, Integer.parseInt(arguments)) : new GrowableFormat(0, 1);
         }

         if ("mid".equals(name)) {
            if (arguments != null && !"".equals(arguments)) {
               String[] args = StringUtils.split(arguments, ',');
               if (args.length != 2) {
                  throw new IllegalArgumentException("invalid arguments for 'mid': " + arguments);
               } else {
                  return new GrowableFormat(Integer.parseInt(args[0]), Integer.parseInt(args[1]));
               }
            } else {
               return new GrowableFormat(1, 1);
            }
         } else {
            return null;
         }
      } catch (NumberFormatException e) {
         LOG.error(LogTypes.CONFIGURATION_ERROR, "Invalid abbreviated message format number for \"" + name + "\": \"" + arguments + "\"", e);
         throw e;
      }
   }

   @SuppressFBWarnings(justification = "generated code")
   private GrowableFormatFactory() {
   }
}
