//
//  tank
//
//  Import and Playlist Daemon for autoradio project
//
//
//  Copyright (C) 2017-2018 Christian Pointner <equinox@helsinki.at>
//
//  This file is part of tank.
//
//  tank is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  any later version.
//
//  tank is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with tank. If not, see <http://www.gnu.org/licenses/>.
//

package importer

import (
	"bufio"
	"io"
	"sync"
)

type convLog struct {
	log []string
	m   *sync.Mutex
}

func newConvLog() *convLog {
	l := &convLog{}
	l.m = &sync.Mutex{}
	return l
}

func (l *convLog) Append(line string) {
	l.m.Lock()
	defer l.m.Unlock()

	l.log = append(l.log, line)
}

type convLogger struct {
	log    *convLog
	prefix string
	s      *bufio.Scanner
	done   chan struct{}
}

func newConvLogger(log *convLog, prefix string, pipe io.Reader) *convLogger {
	l := &convLogger{log: log, prefix: prefix}
	l.s = bufio.NewScanner(pipe)
	l.done = make(chan struct{})
	go l.run()
	return l
}

func (l *convLogger) run() {
	defer close(l.done)

	for l.s.Scan() {
		l.log.Append(l.prefix + l.s.Text())
		// TODO: add this to import log of store as well?
	}
	if err := l.s.Err(); err != nil {
		l.log.Append(l.prefix + l.s.Text())
		// TODO: print this on application error log??
		return
	}

}

func (l *convLogger) Wait() {
	<-l.done
}