package io.muoncore.codec.crypt;

import io.muoncore.codec.Codecs;

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

/**
 * Codecs that wraps another and encrypts/ decrypts on the way past.
 */
public class EncryptingCodecs implements Codecs {

    private Codecs delegate;
    private EncryptionAlgorithm algorithm;

    public EncryptingCodecs(Codecs delegate, EncryptionAlgorithm algorithm) {
        this.delegate = delegate;
        this.algorithm = algorithm;
    }

    @Override
    public EncodingResult encode(Object object, String[] acceptableContentTypes) {
        EncodingResult result = delegate.encode(object, acceptableContentTypes);
        return new EncodingResult(algorithm.encrypt(result.getPayload()),
                result.getContentType() + "+" + algorithm.getAlgorithmName());
    }

    @Override
    public <T> T decode(byte[] source, String contentType, Class<T> type) {
        byte[] decrypted = algorithm.decrypt(source);
        String content = contentType.substring(0, contentType.indexOf("+"));
        return delegate.decode(decrypted, content, type);
    }

    @Override
    public String getBestAvailableCodec(String[] acceptableContentTypes) {
        return delegate.getBestAvailableCodec(acceptableContentTypes) + "+" + algorithm.getAlgorithmName();
    }

    @Override
    public String[] getAvailableCodecs() {
        return Arrays.stream(delegate.getAvailableCodecs()).map(
                codec -> codec + "+" + algorithm.getAlgorithmName()).collect(Collectors.toList()).toArray(new String[0]);
    }
}

@@ -83,17 +83,68 @@
 il.Array
-s
+List;%0Aimport java.util.Arrays;%0Aimport java.util.List
 ;%0Aimport
@@ -1423,23 +1423,149 @@
         
-return 
+List%3CString%3E codecs = new ArrayList%3C%3E();%0A        codecs.addAll(Arrays.asList(delegate.getAvailableCodecs()));%0A%0A        codecs.addAll(
 Arrays.s
@@ -1703,16 +1703,41 @@
 oList())
+);%0A%0A        return codecs
 .toArray
@@ -1748,17 +1748,29 @@
  String%5B
-0
+codecs.size()
 %5D);%0A    

Return both the encrypted and unencrypted codecs.