package utils

import (
	"io"
	"os"
)

func ReaderToFile(reader io.Reader, path string, maxSize ...int64) (writed int64, err error) {
	fd, err := os.Create(path)
	if err != nil {
		return 0, err
	}
	defer fd.Close()

	max := int64(0)
	if len(maxSize) > 0 {
		max = maxSize[0]
	}

	chunkSize := 4096
	if max > 0 && max < int64(chunkSize) {
		chunkSize = int(max)
	}

	buff := make([]byte, chunkSize)
	n := 0

	for n, err = reader.Read(buff[:chunkSize]); n > 0 && chunkSize > 0; n, err = reader.Read(buff[:chunkSize]) {
		fd.Write(buff[:n])
		writed += int64(n)

		if max > 0 && max-writed < int64(chunkSize) {
			chunkSize = int(max - writed)
		}
	}

	if err != nil && err != io.EOF {
		return writed, err
	}

	return writed, nil
}
