package com.qmth.boot.core.fss.utils;

import com.qmth.boot.core.fss.config.FileStoreProperty;
import com.qmth.boot.core.fss.config.FssSecretProvider;
import com.qmth.boot.core.fss.store.FileStore;
import com.qmth.boot.core.fss.store.impl.DiskStore;
import com.qmth.boot.core.fss.store.impl.OssStore;
import com.qmth.boot.tools.models.ByteArray;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

public class FileStoreBuilder {

    public static FileStore buildFileStore(String name, FileStoreProperty fileStoreProperty,
            FssSecretProvider fssSecretProvider) {
        String tempPath = System.getProperty("java.io.tmpdir");
        //格式化server路径
        String server = StringUtils.trimToEmpty(fileStoreProperty.getServer());
        if (!server.endsWith(FssUtils.FILE_PATH_SEPARATOR)) {
            server = server.concat(FssUtils.FILE_PATH_SEPARATOR);
        }
        //server匹配时构造签名工具
        FssSigner fssSigner = null;
        if (server.equals(FssUtils.INNER_ENDPOINT_PREFIX.concat(FssUtils.FILE_PATH_SEPARATOR))) {
            fssSigner = new FssSigner(name, fssSecretProvider.getSecret());
        }
        String config = fileStoreProperty.getConfig();
        if (config.startsWith("oss://")) {
            return new OssStore(new OssConfig(config, server), tempPath);
        } else {
            //disk模式下启用加密时构造加密工具
            String cipherKey = null;
            if (fileStoreProperty.isEncrypt()) {
                cipherKey = ByteArray.sha1(name + ":" + fssSecretProvider.getSecret()).toHexString().substring(0, 16);
            }
            return new DiskStore(config, server, tempPath, fssSigner, cipherKey);
        }
    }

    private static Cipher getCipher(String bucket, FssSecretProvider fssSecretProvider) {
        try {
            Cipher cipher = Cipher.getInstance("AES");
            String keyDigest = ByteArray.sha1(bucket + ":" + fssSecretProvider.getSecret()).toHexString();
            cipher.init(Cipher.ENCRYPT_MODE,
                    new SecretKeySpec(keyDigest.substring(0, 16).getBytes(StandardCharsets.UTF_8), "AES"));
            return cipher;
        } catch (Exception e) {
            throw new RuntimeException("Build cipher error for bucket: " + bucket, e);
        }
    }
}
