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

import com.qmth.boot.core.fss.config.FileStoreProperty;
import com.qmth.boot.core.fss.config.FssSecretProvider;
import com.qmth.boot.core.fss.store.impl.DiskStore;
import com.qmth.boot.core.fss.utils.FileStoreBuilder;
import com.qmth.boot.core.fss.utils.FssUtils;
import com.qmth.boot.tools.models.ByteArray;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Assert;
import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.time.Duration;

public class DiskStoreTest {

    @Test
    public void test() throws Exception {
        FileStoreProperty p = new FileStoreProperty();
        p.setServer(FssUtils.INNER_ENDPOINT_PREFIX);
        p.setConfig(System.getProperty("java.io.tmpdir"));
        FssSecretProvider provider = () -> "qmth";
        DiskStore store = (DiskStore) FileStoreBuilder.buildFileStore("test", p, provider);
        condition(store);
    }

    //@Test
    public void testEncrypt() throws Exception {
        FileStoreProperty p = new FileStoreProperty();
        p.setServer(FssUtils.INNER_ENDPOINT_PREFIX);
        p.setConfig("/Users/luoshi/test");
        p.setEncrypt(true);
        FssSecretProvider provider = () -> "qmth";
        DiskStore store = (DiskStore) FileStoreBuilder.buildFileStore("test", p, provider);
        //condition(store);
        condition(store, new File("/Users/luoshi/Downloads/1.mp4"));
    }

    private void condition(DiskStore store) throws Exception {
        String content = RandomStringUtils.random(128, true, true);
        store.write("/1/123.txt", ByteArray.fromString(content).toInputStream(), ByteArray.md5(content).toBase64());
        Assert.assertTrue(store.exist("1/123.txt"));
        Assert.assertEquals(content, ByteArray.fromInputStream(store.read("1/123.txt")).toString());
        Assert.assertTrue(store.getServerUrl("/1/123.txt", Duration.ofSeconds(30))
                .contains(FssUtils.INNER_ENDPOINT_PARAM_SIGNATURE));
        store.copy("/1/123.txt", "2/321.txt");
        Assert.assertTrue(store.exist("2/321.txt"));
        Assert.assertEquals(content, ByteArray.fromInputStream(store.read("2/321.txt")).toString());
        store.delete("/1/123.txt");
        Assert.assertFalse(store.exist("1/123.txt"));
    }

    private void condition(DiskStore store, File file) throws Exception {
        String md5 = ByteArray.md5(file).toBase64();
        String path = "/1/1.file";
        store.write(path, new FileInputStream(file), md5);
        Assert.assertTrue(store.exist(path));
        Assert.assertEquals(md5, ByteArray.md5(ByteArray.fromInputStream(store.read(path)).value()).toBase64());
    }
}
