package producer

import (
	"bytes"
	"html"
	"os"

	"text/template"
)

var HDRTemplate = `ENVI
description = {
  File Imported into ENVI.}
samples = {{.Samples}}
lines = {{.Lines}}
bands = {{.Bands}}
header offset = 0
file type = ENVI Standard
data type = 12
interleave = bsq
sensor type = Unknown
byte order = 0
wavelength units = Unknown`

// https://www.nv5geospatialsoftware.com/docs/ENVIHeaderFiles.html
type EnviHdr struct {
	Samples int // samples (pixels) each line
	Lines   int
	Bands   int
}

func (h *EnviHdr) String() string {
	var t *template.Template
	t = template.New("template")
	t, err := t.Parse(HDRTemplate)
	if err != nil {
		return ""
	}
	buf := new(bytes.Buffer)
	t.Execute(buf, h)
	buf = bytes.NewBufferString(html.UnescapeString(buf.String()))

	return buf.String()
}

func (h *EnviHdr) Write(filename string) error {
	str := h.String()
	f, err := os.Create(filename)
	if err != nil {
		return err
	}
	defer f.Close()
	_, err = f.WriteString(str)
	return err
}
