package com.atlassian.bitbucket.scm.git.protocol;

import com.google.common.base.Charsets;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Nonnull;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

/**
 * Utility class that can be used for classifying git packets
 *
 * @since 4.9
 */
public class GitPackets {
    private static final byte[] DONE = "0008done".getBytes(StandardCharsets.UTF_8);
    private static final byte[] DONE_LINE = "0009done\n".getBytes(StandardCharsets.UTF_8);
    private static final byte[] FLUSH = "0000".getBytes(StandardCharsets.UTF_8);

    private GitPackets() {
        // utility class; should not be instantiated
    }

    @Nonnull
    public static byte[] create(@Nonnull String value) {
        byte[] valueBytes = value.getBytes(Charsets.UTF_8);
        String length = StringUtils.leftPad(Integer.toHexString(valueBytes.length + 4), 4, "0");
        byte[] packet = new byte[valueBytes.length + 4];
        System.arraycopy(length.getBytes(Charsets.UTF_8), 0, packet, 0, 4);
        System.arraycopy(valueBytes, 0, packet, 4, valueBytes.length);
        return packet;
    }


    @Nonnull
    public static byte[] getFlush() {
        return FLUSH.clone();
    }

    public static boolean isDone(byte[] packet) {
        return packet != null && Arrays.equals(DONE, packet) || Arrays.equals(DONE_LINE, packet);
    }

    public static boolean isFlush(byte[] packet) {
        return packet != null && Arrays.equals(FLUSH, packet);
    }

    @Nonnull
    public static String toLine(byte[] packet) {
        if (packet == null || packet.length < 4) {
            throw new IllegalArgumentException("Git packets need to be at least 4 bytes long");
        }
        if (isFlush(packet)) {
            return "";
        }
        return new String(packet, 4, packet.length - 4, StandardCharsets.UTF_8);
    }
}
