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

// reader.go
package file

import (
	"bufio"
	"io"
	"os"
)

type Reader struct {
	// fh     *os.File
	handleBase
	reader *bufio.Reader
}

func NewReader(fh *os.File) *Reader {
	return &Reader{handleBase: handleBase{fh: fh}, reader: bufio.NewReader(fh)}
}

func OpenReader(filePath string) (r *Reader, err error) {
	var fh *os.File
	if fh, err = os.Open(filePath); err == nil {
		r = NewReader(fh)
	}
	return
}

func (h *Reader) TypeName() string {
	return "fileReader"
}

func (h *Reader) String() string {
	return "reader"
}

func (h *Reader) Valid() bool {
	return h.handleBase.Valid() && h.reader != nil
}

func (w *Reader) Close() (err error) {
	w.reader = nil
	err = w.handleBase.Close()
	return
}

func (h *Reader) ReadByte() (b byte, err error) {
	if h.reader != nil {
		b, err = h.reader.ReadByte()
	} else {
		err = io.ErrClosedPipe
	}
	return
}

func (h *Reader) ReadAll() (p []byte, err error) {
	if h.reader != nil {
		p, err = io.ReadAll(h.reader)
	} else {
		err = io.ErrClosedPipe
	}
	return
}

func (h *Reader) ReadString(delim byte) (s string, err error) {
	if h.reader != nil {
		s, err = h.reader.ReadString(delim)
	} else {
		err = io.ErrClosedPipe
	}
	return
}

func (h *Reader) Reset() (err error) {
	if h.fh != nil {
		if _, err = h.fh.Seek(0, 0); err == nil {
			h.reader.Reset(h.fh)
		}
	}
	return
}
