package com.munjaon.client.server.packet;

import java.nio.ByteBuffer;

public final class Packet {
    public static final byte SET_DEFAULT_BYTE = (byte) 0x00;
    public static final long LINK_CHECK_CYCLE = 10000L;
//    public static final long LINK_CHECK_CYCLE = 30000L;

    public static void setDefaultByte(ByteBuffer buffer) {
        if (buffer == null) {
            return;
        }
//        buffer.clear();
        for (int i = 0; i < buffer.capacity(); i++) {
            buffer.put(i, SET_DEFAULT_BYTE);
        }
//        buffer.position(0);
    }

    public static String getString(byte[] srcArray) {
        if (srcArray == null) {
            return null;
        }
        int size = 0;
        for (int i = 0, len = srcArray.length; i < len; i++) {
            if (srcArray[i] == SET_DEFAULT_BYTE) {
                continue;
            }
            size++;
        }
        byte[] destArray = null;
        if (size > 0) {
            destArray  = new byte[size];
            int index = 0;
            for (int i = 0, len = srcArray.length; i < len; i++) {
                if (srcArray[i] == SET_DEFAULT_BYTE) {
                    continue;
                }
                destArray[index++] = srcArray[i];
            }
        }

        return destArray == null ? null : new String(destArray);
    }

    public static void mergeBuffers(ByteBuffer dest, ByteBuffer srcHead, ByteBuffer srcBody) {
        if (dest == null || srcHead == null || srcBody == null) {
            return;
        }
        if (dest.capacity() != (srcHead.capacity() + srcBody.capacity())) {
            return;
        }
        for (int i = 0; i < srcHead.capacity(); i++) {
            dest.put(i, srcHead.get(i));
        }
        for (int i = 0; i < srcBody.capacity(); i++) {
            dest.put((i + srcHead.capacity()), srcBody.get(i));
        }
//        byte[] srcHeadArray = srcHead.array();
//        byte[] srcBodyArray = srcBody.array();
//
//        dest.put(0, srcHeadArray);
//        dest.put(srcHeadArray.length, srcBodyArray);
    }

    public static void printBuffer(ByteBuffer buffer) {
        if (buffer == null) {
            return;
        }
        for (int i = 0; i < buffer.capacity(); i++) {
            System.out.print(buffer.get(i) + " ");
        }
    }
}
