package dev.elaine.network;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public final class FileTransferSample {
    private FileTransferSample() {}

    public static long copyWithBuffer(Path source, Path target) throws IOException {
        long copied = 0;
        try (FileChannel input = FileChannel.open(source, StandardOpenOption.READ);
             FileChannel output = FileChannel.open(target, StandardOpenOption.CREATE,
                     StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) {
            ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);
            while (input.read(buffer) >= 0) {
                buffer.flip();
                while (buffer.hasRemaining()) {
                    copied += output.write(buffer);
                }
                buffer.clear();
            }
        }
        return copied;
    }

    public static long copyWithTransferTo(Path source, Path target) throws IOException {
        try (FileChannel input = FileChannel.open(source, StandardOpenOption.READ);
             FileChannel output = FileChannel.open(target, StandardOpenOption.CREATE,
                     StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) {
            long position = 0;
            while (position < input.size()) {
                long transferred = input.transferTo(position, input.size() - position, output);
                if (transferred == 0) {
                    break;
                }
                position += transferred;
            }
            return position;
        }
    }
}

