package com.atlassian.stash.internal.hazelcast;

import com.atlassian.stash.internal.license.SimpleDualLicense;
import com.atlassian.stash.internal.license.LicenseHelper;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.StreamSerializer;

import java.io.IOException;

/**
 * Serializes {@link SimpleDualLicense} instances by writing out the {@link SimpleDualLicense#getEncodedLicense()
 * encoded license} and deserializes by {@link LicenseHelper#decode(String) decoding} the license again.
 *
 * @since 3.2
 * @see SimpleDualLicense
 */
public class LicenseStreamSerializer implements StreamSerializer<SimpleDualLicense> {

    private final LicenseHelper licenseHelper;

    public LicenseStreamSerializer(LicenseHelper licenseHelper) {
        this.licenseHelper = licenseHelper;
    }

    @Override
    public void destroy() {
    }

    @Override
    public int getTypeId() {
        return HazelcastConstants.TYPE_LICENSE;
    }

    @Override
    public SimpleDualLicense read(ObjectDataInput in) throws IOException {
        String encoded = in.readUTF();

        return (SimpleDualLicense) licenseHelper.decode(encoded);
    }

    @Override
    public void write(ObjectDataOutput out, SimpleDualLicense license) throws IOException {
        out.writeUTF(license.getEncodedLicense());
    }
}
