package storage

import (
	"archive/zip"
	"io"
	"os"
)

func ZipFiles(files []FileUpload, w io.Writer) error {
	zipWriter := zip.NewWriter(w)
	defer zipWriter.Close()

	// Add files to zip
	for _, file := range files {
		if err := AddFileToZip(zipWriter, file); err != nil {
			return err
		}
	}

	return nil
}

// https://golangcode.com/create-zip-files-in-go/
func AddFileToZip(zipWriter *zip.Writer, file FileUpload) error {
	fileToZip, err := os.Open(GetStoreDestination(file.SHA256 + file.FileExt))
	if err != nil {
		return err
	}

	defer fileToZip.Close()

	// get file info
	info, err := fileToZip.Stat()
	if err != nil {
		return err
	}

	header, err := zip.FileInfoHeader(info)
	if err != nil {
		return err
	}

	// Reset original file name
	header.Name = file.FileName

	// Change to deflate for better compression
	header.Method = zip.Deflate

	writer, err := zipWriter.CreateHeader(header)
	if err != nil {
		return err
	}

	_, err = io.Copy(writer, fileToZip)

	return nil
}
