package mfer

import (
	"io"
	"os"
)

// WriteToFile writes the manifest to the given path.
// It will overwrite any existing file. Callers should check for existing files
// before calling if overwrite confirmation is needed.
func (m *manifest) WriteToFile(path string) error {
	f, err := os.Create(path)
	if err != nil {
		return err
	}
	defer func() { _ = f.Close() }()

	return m.Write(f)
}

func (m *manifest) Write(output io.Writer) error {
	if m.pbOuter == nil {
		err := m.generate()
		if err != nil {
			return err
		}
	}

	_, err := output.Write(m.output.Bytes())
	if err != nil {
		return err
	}
	return nil
}
