package watchlog

import (
	"github.com/gorilla/websocket"
	"github.com/hpcloud/tail"

	"git.kingpenguin.tk/chteufleur/datahouse.git/models"
	"git.kingpenguin.tk/chteufleur/datahouse.git/models/variables"

	"container/list"
	"time"
)

const (
	EndRun = "EndRunWatchlog"
)

var (
	ListWebSocket = list.New()
)

func Run() {
	t, _ := tail.TailFile(variables.LogFilePath, tail.Config{Follow: true})
	for line := range t.Lines {
		broadcastWebSocket(line.Text)
	}
	time.Sleep(30 * time.Second)
	models.ChanRuns <- EndRun
}

func broadcastWebSocket(message string) {
	for sub := ListWebSocket.Front(); sub != nil; sub = sub.Next() {
		// Immediately send event to WebSocket users.
		ws := sub.Value.(*websocket.Conn)
		err := ws.WriteMessage(websocket.TextMessage, []byte(message))
		if err != nil {
			toRemove := sub
			sub = sub.Prev()
			ListWebSocket.Remove(toRemove)
			break
		}
	}
}
