package cn.palmte.work.model.process;

import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import javax.persistence.AttributeConverter;

import cn.palmte.work.model.enums.Enumerable;
import cn.palmte.work.model.enums.SealType;

/**
 * @author <a href="https://github.com/TAKETODAY">Harry Yang</a>
 * @since 2.0 2022/12/14 16:36
 */
public class SealTypeArrayConverter implements AttributeConverter<SealTypeArray, String> {

  @Override
  public String convertToDatabaseColumn(SealTypeArray attribute) {
    List<SealType> sealTypes = attribute.getList();
    if (sealTypes.isEmpty()) {
      return null;
    }
    return sealTypes.stream()
            .map(SealType::getValue)
            .collect(Collectors.joining(","));
  }

  @Override
  public SealTypeArray convertToEntityAttribute(String dbData) {
    return Optional.ofNullable(dbData)
            .filter(StringUtils::hasText)
            .map(data -> data.split(","))
            .map(Arrays::stream)
            .map(stream -> stream.map(element -> Enumerable.of(SealType.class, element))
                    .toArray(SealType[]::new))
            .map(SealTypeArray::of)
            .orElse(SealTypeArray.EMPTY);
  }

}
