/*
** Job Arranger for ZABBIX
** Copyright (C) 2025 Daiwa Institute of Research Ltd. All Rights Reserved.
**
** This program 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 2 of the License, or
** (at your option) any later version.
**
** This program 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 this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
**/
package watcher

import (
	"log"
	"regexp"

	"github.com/fsnotify/fsnotify"
)

func StartWatcher(path string, pattern string, watchEvents fsnotify.Op, doneFileChan chan<- string) {
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatal("Failed to initialize watcher:", err)
	}
	defer watcher.Close()

	err = watcher.Add(path)
	if err != nil {
		log.Fatal("Failed to add path to watcher:", err)
	}

	regex, err := regexp.Compile(pattern)
	if err != nil {
		log.Fatalf("Failed to compile regex pattern: %v", err)
	}

	log.Println("Inotify watcher started on directory:", path)
	// log.Println("Watching for file:", targetFilename)

	for {
		select {
		case event, ok := <-watcher.Events:
			if !ok {
				return
			}

			if event.Op&watchEvents != 0 {
				if regex.MatchString(event.Name) {
					log.Printf("Detected matching file: %s", event.Name)
					doneFileChan <- event.Name
				}
			}

		case err, ok := <-watcher.Errors:
			if !ok {
				return
			}
			log.Println("Watcher error:", err)
		}
	}
}
