package com.alterdekim.game.xml;

import com.alterdekim.game.controller.result.async.ServerActionCData;
import com.alterdekim.game.crypto.RC4;
import com.alterdekim.game.utils.StringUtils;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.List;

@Slf4j
public class CryptoSerializer extends JsonSerializer<List<ServerActionCData>> {
    private static final String S = "<cdata value=\"%s\" />\r\n";

    @Override
    public void serialize(List<ServerActionCData> list, JsonGenerator generator, SerializerProvider provider) throws IOException {
        for( ServerActionCData v : list ) {
            String s = String.format(S, StringUtils.bytesToHex(new RC4("_level0".getBytes()).encrypt(
                            new XmlMapper()
                                    .setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)
                                    .writeValueAsBytes(v)
                    )).toLowerCase()
            );
            generator.writeRaw(s);
        }
        //generator.writeNull();
    }
}
