package statusline

import (
	"io"
	"time"
)

type AsyncStatusLine struct {
	lines chan string
	end   chan struct{}
}

func NewAsyncStatusLine(out io.Writer, d time.Duration) *AsyncStatusLine {
	ret := &AsyncStatusLine{
		lines: make(chan string),
		end:   make(chan struct{}),
	}
	go func() {
		sl := NewStatusLine(out)
		ticker := time.NewTicker(d)
		var line string
		for {
			select {
			case <-ticker.C:
				sl.Put(line)
			case l := <-ret.lines:
				line = l
			case <-ret.end:
				sl.End()
				ticker.Stop()
			}
		}
	}()
	return ret
}

func (sl *AsyncStatusLine) Put(line string) {
	sl.lines <- line
}

func (sl *AsyncStatusLine) End() {
	sl.end <- struct{}{}
	close(sl.lines)
	close(sl.end)
}