package org.apache.commons.beanutils.converters;

import java.util.List;
import org.apache.commons.beanutils.ConversionException;

public final class BooleanArrayConverter extends AbstractArrayConverter {
  public BooleanArrayConverter() {
    this.defaultValue = null;
    this.useDefault = false;
  }
  
  public BooleanArrayConverter(Object defaultValue) {
    this.defaultValue = defaultValue;
    this.useDefault = true;
  }
  
  private static boolean[] model = new boolean[0];
  
  public Object convert(Class type, Object value) {
    if (value == null) {
      if (this.useDefault)
        return this.defaultValue; 
      throw new ConversionException("No value specified");
    } 
    if (model.getClass() == value.getClass())
      return value; 
    if (AbstractArrayConverter.strings.getClass() == value.getClass())
      try {
        String[] values = (String[])value;
        boolean[] results = new boolean[values.length];
        for (int i = 0; i < values.length; i++) {
          String stringValue = values[i];
          if (stringValue.equalsIgnoreCase("yes") || stringValue.equalsIgnoreCase("y") || stringValue.equalsIgnoreCase("true") || stringValue.equalsIgnoreCase("on") || stringValue.equalsIgnoreCase("1")) {
            results[i] = true;
          } else if (stringValue.equalsIgnoreCase("no") || stringValue.equalsIgnoreCase("n") || stringValue.equalsIgnoreCase("false") || stringValue.equalsIgnoreCase("off") || stringValue.equalsIgnoreCase("0")) {
            results[i] = false;
          } else {
            if (this.useDefault)
              return this.defaultValue; 
            throw new ConversionException(value.toString());
          } 
        } 
        return results;
      } catch (Exception e) {
        if (this.useDefault)
          return this.defaultValue; 
        throw new ConversionException(value.toString(), e);
      }  
    try {
      List list = parseElements(value.toString());
      boolean[] results = new boolean[list.size()];
      for (int i = 0; i < results.length; i++) {
        String stringValue = list.get(i);
        if (stringValue.equalsIgnoreCase("yes") || stringValue.equalsIgnoreCase("y") || stringValue.equalsIgnoreCase("true") || stringValue.equalsIgnoreCase("on") || stringValue.equalsIgnoreCase("1")) {
          results[i] = true;
        } else if (stringValue.equalsIgnoreCase("no") || stringValue.equalsIgnoreCase("n") || stringValue.equalsIgnoreCase("false") || stringValue.equalsIgnoreCase("off") || stringValue.equalsIgnoreCase("0")) {
          results[i] = false;
        } else {
          if (this.useDefault)
            return this.defaultValue; 
          throw new ConversionException(value.toString());
        } 
      } 
      return results;
    } catch (Exception e) {
      if (this.useDefault)
        return this.defaultValue; 
      throw new ConversionException(value.toString(), e);
    } 
  }
}
