# coding: utf-8

module RedminePluginloader
module Patches
  module PluginloaderPatch

    def self.included(base)
      base.extend ClassMethods
      base.send(:include, InstanceMethods)
      base.class_eval do
        cattr_accessor :plugin_requirements

        class << self
          alias_method_chain :register, :pluginloader
        end

        alias_method_chain :requires_redmine_plugin, :pluginloader
      end
    end

    module InstanceMethods
      def requires_redmine_plugin_with_pluginloader(plugin_name, arg, &block)
        self.class.plugin_requirements << [id, plugin_name, arg]
      end
    end

    module ClassMethods
      def register_with_pluginloader(id, &block)
        self.plugin_requirements ||= [ ]
        register_without_pluginloader(id, &block)
      end

      def check_plugin_requirements
        self.plugin_requirements.each do |id, dep, arg|
          plugin = self.find(id)
          begin
            plugin.requires_redmine_plugin_without_pluginloader(dep, arg)
          rescue ::Redmine::PluginNotFound => e
            raise ::Redmine::PluginRequirementError,
                "#{id} plugin requires the #{dep} plugin, which is not installed.",
                $!.backtrace
          end
        end
      end
    end
  end

  unless ::Redmine::Plugin.included_modules.include?(PluginloaderPatch)
    ::Redmine::Plugin.send(:include, PluginloaderPatch)
  end
end
end
