require_relative "rubysermon/version"
require_relative "rubysermon/mod_loader"
require_relative "rubysermon/mod_template"
require_relative "rubysermon/configurator"

require "date"

module Rubysermon
	LIB_PATH = File.expand_path(File.dirname(__FILE__))
	APP_PATH = "#{LIB_PATH}/.."
	MOD_PATH = "#{LIB_PATH}/rubysermon/mod"

	class App
		attr_accessor :config_path

		def initialize
			@config 		= {repeat: 60}
			@running_mods	= []
			@config_path	= "#{LIB_PATH}/rubysermon/config.json"
			@enabled_mods	= []
		end

		def run
			read_config()
			enable_and_start_mods()

			if (msg = cannot_start_fetch_process_sleep_cycle?)
				abort(msg)
			end

			start_fetch_process_sleep_cycle()
		end

		private

		def read_config
			configurator = Configurator.new(@config_path)
			config = configurator.get_settings()
			@config.merge!(config)
		end

		def enable_and_start_mods
			@enabled_mods = @config[:modules].to_a
			@enabled_mods.each do |mod| load_mod(mod) end
		end

		def load_mod(mod_name)
			begin
				mod = ModLoader.load(mod_name)
				@running_mods.push(mod)
			rescue ModLoaderException => e
				$stderr.puts e.message
			end
		end

		def cannot_start_fetch_process_sleep_cycle?
			if @config[:repeat].to_i < 1
				return "Repeat cycle is too short"
			elsif @running_mods.empty?
				return "There are no enabled modules"
			end

			false
		end

		def start_fetch_process_sleep_cycle
			while true
				current_time = DateTime.now()
				@running_mods.each do |mod|
					result = mod.results
					notify = mod.notify?
				end
				sleep @config[:repeat]
			end
		end
	end
end