package sse

import (
	"bufio"
	"io"
	"strings"
)

// ForEachLine reads line-oriented SSE content without bufio.Scanner's token limit.
func ForEachLine(r io.Reader, fn func(string) error) error {
	reader := bufio.NewReader(r)

	for {
		line, err := reader.ReadString('\n')
		if err != nil && err != io.EOF {
			return err
		}

		if len(line) > 0 {
			line = strings.TrimRight(line, "\r\n")
			if callErr := fn(line); callErr != nil {
				return callErr
			}
		}

		if err == io.EOF {
			return nil
		}
	}
}
