# frozen_string_literal: true

# Released under the MIT License.
# Copyright, 2021-2026, by Samuel Williams.

require "set"

require_relative "handle"

module Build
	module Files
		module Monitor
			# A cross-platform filesystem monitor that uses polling to detect changes.
			# 
			# This implementation works on all platforms by periodically checking file modification times. While less efficient than platform-specific native implementations, it provides a reliable fallback for platforms without native filesystem event support.
			class Polling
				# Initialize a new polling monitor.
				def initialize
					@directories = Hash.new do |hash, key|
						hash[key] = Set.new
					end
					
					@updated = false
					
					@deletions = nil
				end
				
				# @attribute [Boolean] Whether the set of monitored directories has been updated.
				attr :updated
				
				# Notify the monitor that files in these directories have changed.
				def update(directories, *args)
					delay_deletions do
						directories.each do |directory|
							@directories[directory].each do |handle|
								# Changes here may not actually require an update to the handle:
								handle.changed!(*args)
							end
						end
					end
				end
				
				# @returns [Array(String)] The root directories currently being monitored.
				def roots
					@directories.keys
				end
				
				# Delete a handle from the monitor.
				# 
				# @parameter handle [Handle] The handle to remove.
				def delete(handle)
					if @deletions
						@deletions << handle
					else
						purge(handle)
					end
				end
				
				# Track changes to a set of files.
				# 
				# @parameter files [List] The list of files to monitor.
				# @yields {|state| ...} When changes are detected.
				# 	@parameter state [State] The current state with information about added, changed, and removed files.
				# @returns [Handle] A handle that can be used to stop tracking these files.
				def track_changes(files, &block)
					handle = Handle.new(self, files, &block)
					
					add(handle)
				end
				
				# Add a handle to the monitor.
				# 
				# @parameter handle [Handle] The handle to add.
				# @returns [Handle] The added handle.
				def add(handle)
					handle.directories.each do |directory|
						# We want the full path as a plain string:
						directory = directory.to_s
						
						@directories[directory] << handle
						
						# We just added the first handle:
						if @directories[directory].size == 1
							# If the handle already existed, this might trigger unnecessarily.
							@updated = true
						end
					end
					
					handle
				end
				
				# Run the monitor loop, checking for changes at regular intervals.
				# 
				# This method blocks until interrupted via `throw :interrupt`. It continuously polls the filesystem for changes and invokes registered callbacks.
				# 
				# @parameter latency [Numeric] The time in seconds to wait between checks (default: 0.1).
				# @yields After each check cycle.
				def run(latency: 0.1, **options, &block)
					catch(:interrupt) do
						while true
							self.update(self.roots)
							
							yield if block_given?
							
							sleep(latency)
						end
					end
				end
				
				protected
				
				def delay_deletions
					@deletions = []
					
					yield
					
					@deletions.each do |handle|
						purge(handle)
					end
					
					@deletions = nil
				end
				
				def purge(handle)
					handle.directories.each do |directory|
						directory = directory.to_s
						
						@directories[directory].delete(handle)
						
						# Remove the entire record if there are no handles:
						if @directories[directory].size == 0
							@directories.delete(directory)
							
							@updated = true
						end
					end
				end
			end
		end
	end
end
