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

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

			config()
			@enabled_mods = @config[:modules].to_a

			start_mods()
			start_fetch_process_sleep_cycle()
		end

		private

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

		def start_mods
			@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 = e.message
			end
		end

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

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

		def cannot_start_fetch_process_sleep_cycle?
			if @config[:repeat].to_i < 1
				return "Repeat cycle too short"
			end

			false
		end
	end
end