package com.samsung.config;

import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.jasypt.encryption.StringEncryptor;
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Log4j2
@Configuration
public class JasyptConfig {

    @Value("${jasypt.encryptor.pool-size:PBEWithMD5AndDES}")
    private String ALGORITHM;

    @Value("${jasypt.encryptor.key-obtention-iterations:1000}")
    private String CNT;

    @Value("${jasypt.encryptor.pool-size:1}")
    private String POOL_SIZE;

    @Value("${jasypt.encryptor.string-output-type:base64}")
    private String BASE64;

    @Value("${jasypt.encryptor.password-property-name:JASYPT_KEY}")
    private String passwordPropertyName;

    @Bean("jasyptStringEncryptor")
    public StringEncryptor stringEncryptor() throws Exception {
        String password = getPassword();

        if (StringUtils.isEmpty(password))
            throw new Exception("can not find encrypt/decrypt password. please confirm environment variable");

        SimpleStringPBEConfig config = new SimpleStringPBEConfig();
        config.setPassword(password);
        config.setAlgorithm(ALGORITHM);
        config.setKeyObtentionIterations(CNT);
        config.setPoolSize(POOL_SIZE);
        config.setStringOutputType(BASE64);

        PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
        encryptor.setConfig(config);
        return encryptor;
    }

    private String getPassword() {
        return StringUtils.isNotEmpty(System.getenv(passwordPropertyName)) ? System.getenv(passwordPropertyName) : System.getProperty(passwordPropertyName);
    }
}
