package com.izouma.nineth.converter;

import com.izouma.nineth.utils.AESEncryptUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

@Converter
@Slf4j
public class EncryptConverter implements AttributeConverter<String, String> {

    @Override
    public String convertToDatabaseColumn(String s) {
        if (StringUtils.isNotBlank(s)) {
            try {
                return "*" + AESEncryptUtil.encrypt(s);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return s;
    }

    @Override
    public String convertToEntityAttribute(String s) {
        if (StringUtils.isNotBlank(s) && s.startsWith("*")) {
            try {
                return AESEncryptUtil.decrypt(s.substring(1));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return s;
    }
}
