package mark2web

import (
	"compress/gzip"
	"io"
	"io/ioutil"
	"os"
	"path"

	"gitbase.de/apairon/mark2web/pkg/jobm"

	"gitbase.de/apairon/mark2web/pkg/logger"
)

func handleCompression(filename string, content []byte) {
	jobm.Enqueue(jobm.Job{
		Function: func() {
			if _, ok := Config.Compress.Extensions[path.Ext(filename)]; ok {

				if Config.Compress.Brotli {
					handleBrotliCompression(filename, content)
				}

				if Config.Compress.GZIP {
					gzFilename := filename + ".gz"

					logger.I("writing to compressed output file: %s", gzFilename)

					f, err := os.Create(gzFilename)
					logger.Eexit(err, "could not create file '%s'", gzFilename)
					defer f.Close()

					zw, err := gzip.NewWriterLevel(f, gzip.BestCompression)
					logger.Eexit(err, "could not initialize gzip writer for '%s'", filename)
					defer zw.Close()

					if content != nil {
						// content given
						_, err = zw.Write(content)
						logger.Eexit(err, "could not write gziped content for '%s'", filename)
					} else {
						// read file
						r, err := os.Open(filename)
						logger.Eexit(err, "could not open file '%s'", filename)
						defer r.Close()

						_, err = io.Copy(zw, r)
						logger.Eexit(err, "could not gzip file '%s'", filename)
					}

				}
			}
		},
		Description: filename,
		Category:    "compress",
	})
}

func compressFilesInDir(dir string) {
	logger.N("compressing configured files in: %s", dir)

	var _processDir func(string)
	_processDir = func(d string) {
		entries, err := ioutil.ReadDir(d)
		logger.Eexit(err, "could not read dir '%s'", d)

		for _, entry := range entries {
			if entry.IsDir() {
				_processDir(d + "/" + entry.Name())
			} else {
				handleCompression(d+"/"+entry.Name(), nil)
			}
		}
	}

	_processDir(dir)

}
