#!/usr/bin/ruby

require 'active_support'
require 'active_support/core_ext'
require_relative 'mail_ops'
require_relative 'log_task'

##
# Receives task and calls run() every n seconds (interval set in task)
# If run() returns false, an alert is sent (by email)
#
def launch_task(task)
	LogTask.info "Starting Thread for alert task '#{task.get_name}'"
	while true
		LogTask.debug "running #{task.get_name} at: #{Time.now}"
		b,str = task.run
		if !b
			LogTask.warn "fail: send alert #{task.get_name} : #{str}"
			MailOps.send_message(task.get_alertemail, "FAIL: #{task.get_name}", ENV["ALERT_FROM_ADDRESS"], str)
		else
			LogTask.debug "No error for task #{task.get_name}"
		end
		sleep(task.get_intervalinsecs)
	end
end

def wait_for_threads(arr)
	arr.each do |item|
		item.join
	end
end

##############################################################

threads = Array.new
tasks = Array.new

LogTask.info "Starting"

# Loads all classes/files with name Task*/task*
Dir["./task*.rb"].each do |file| 
	require file
	file_name = File.basename(File.path(file), '.rb')

	# Instantiate class
	task = file_name.camelcase.constantize.new

	LogTask.info "loading #{file_name.camelcase} in #{file}"

	# Add to task array (probably needed in a future requirement)
	tasks << task

	# Start thread and add to thread array
	threads << Thread.new{launch_task(task)}
end

# Waits for all threads to finish
wait_for_threads(threads)

