
package de.ivu.elect.business.exchange.boundary;

import java.util.ArrayList;

import de.ivu.elect.business.datei.entity.CsvMaskierungszeichen;


import static de.ivu.elect.business.exchange.boundary.ExchangeValueDecorators.MESSAGES_DECORATOR_CSV_INJECTION;
import static de.ivu.elect.business.exchange.boundary.ExchangeValueDecorators.MESSAGES_DECORATOR_NULL_TO_EMPTY;
import static de.ivu.elect.business.exchange.boundary.ExchangeValueDecorators.MESSAGES_DECORATOR_REMOVE_SHY;
import static java.util.Arrays.asList;

public class ExchangeStringConverter implements ExchangeTypeConverter {

  private static final String ESCAPE_CHARACTER = Character.toString(CsvMaskierungszeichen.BACKSLASH.getCharacter());

  private static final String ESCAPE_CHARACTER_ESCAPED = ESCAPE_CHARACTER + ESCAPE_CHARACTER;

  private final ExchangeValueDecorators exchangeValueDecorators;

  public ExchangeStringConverter(ExchangeValueDecorators exchangeValueDecorators) {
    super();

    this.exchangeValueDecorators = exchangeValueDecorators;
  }

  @Override
  public String toString(Object value) {
    if (value != null) {
      String result = value.toString();

      result = result.replace(ESCAPE_CHARACTER, ESCAPE_CHARACTER_ESCAPED);

      result = exchangeValueDecorators.apply(result); // ELECT-6722, ELECT-5329

      return result;
    }

    return null;
  }

  @Override
  public String fromString(String value) {
    if (value != null) {
      String result = value;
      result = result.replace(ESCAPE_CHARACTER_ESCAPED, ESCAPE_CHARACTER);

      return result;
    }

    return null;
  }

  public static ExchangeStringConverter createExchangeStringConverterWithoutValueDecorators() {
    ExchangeValueDecorators exchangeValueDecorators = new ExchangeValueDecorators(new ArrayList<>());

    return new ExchangeStringConverter(exchangeValueDecorators);
  }

  public static ExchangeStringConverter createDefaultExchangeStringConverter() {
    ExchangeValueDecorators exchangeValueDecorators = new ExchangeValueDecorators(asList(
        MESSAGES_DECORATOR_NULL_TO_EMPTY,
        MESSAGES_DECORATOR_REMOVE_SHY
    ));

    return new ExchangeStringConverter(exchangeValueDecorators);
  }

  public static ExchangeStringConverter createExchangeCsvStringConverter() {
    ExchangeValueDecorators exchangeValueDecorators = new ExchangeValueDecorators(asList(
        MESSAGES_DECORATOR_NULL_TO_EMPTY,
        MESSAGES_DECORATOR_REMOVE_SHY,
        MESSAGES_DECORATOR_CSV_INJECTION
    ));

    return new ExchangeStringConverter(exchangeValueDecorators);
  }
}
