package watcher

import (
	"log"

	"github.com/fsnotify/fsnotify"
)

type Files struct {
	List []string
}

type OnModify func()

func New() *Files {
	return &Files{}
}

func (f *Files) Add(file string) {
	f.List = append(f.List, file)
}

func (f *Files) Run(fn OnModify) {
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}
	defer watcher.Close()

	done := make(chan bool)
	go func() {
		for {
			select {
			case event, ok := <-watcher.Events:
				if !ok {
					return
				}
				if event.Op&fsnotify.Write == fsnotify.Write {
					fn()
				}
			case _, ok := <-watcher.Errors:
				if !ok {
					return
				}
			}
		}
	}()

	for _, item := range f.List {
		err = watcher.Add(item)
		if err != nil {
			log.Fatal(err)
		}
	}
	<-done
}
