// Copyright (c) 2024-2026 Celestino Amoroso (celestino.amoroso@gmail.com).
// All rights reserved.

// writer.go
package file

import (
	"bufio"
	"fmt"
	"os"
)

type Writer struct {
	// fh     *os.File
	handleBase
	writer *bufio.Writer
}

func NewWriter(fh *os.File) *Writer {
	return &Writer{handleBase: handleBase{fh: fh}, writer: bufio.NewWriter(fh)}
}

func CreateWriter(filePath string) (w *Writer, err error) {
	var fh *os.File
	if fh, err = os.Create(filePath); err == nil {
		w = NewWriter(fh)
	}
	return
}

func AppendWriter(filePath string) (w *Writer, err error) {
	var fh *os.File
	if fh, err = os.OpenFile(filePath, os.O_APPEND|os.O_WRONLY, 0644); err == nil {
		w = NewWriter(fh)
	}
	return
}

func (w *Writer) TypeName() string {
	return "fileWriter"
}

func (w *Writer) String() string {
	return "writer"
}

func (w *Writer) Valid() bool {
	return w.handleBase.Valid() && w.writer != nil
}

func (w *Writer) Close() (err error) {
	var err1 error
	if w.writer != nil {
		err1 = w.Flush()
		w.writer = nil
	}
	if err = w.handleBase.Close(); err == nil {
		err = err1
	}
	return
}

func (w *Writer) Flush() (err error) {
	if w.writer != nil {
		err = w.writer.Flush()
	}
	return
}

func (w *Writer) Write(args ...any) (n int, err error) {
	if w.writer != nil {
		n, err = fmt.Fprint(w.writer, args...)
	}
	return
}

func (w *Writer) Writef(format string, args ...any) (n int, err error) {
	if w.writer != nil {
		n, err = fmt.Fprintf(w.writer, format, args...)
	}
	return
}
