# Redmine - project management software
# Copyright (C) 2006-2013  Jean-Philippe Lang
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

module Redmine
  module Acts
    module ActivityProvider
      def self.included(base)
        base.extend ClassMethods
      end

      module ClassMethods
        def acts_as_activity_provider(options = {})
          unless self.included_modules.include?(Redmine::Acts::ActivityProvider::InstanceMethods)
            cattr_accessor :activity_provider_options
            send :include, Redmine::Acts::ActivityProvider::InstanceMethods
          end

          options.assert_valid_keys(:type, :permission, :timestamp, :author_key, :find_options, :func,:is_public)
          self.activity_provider_options ||= {}

          # One model can provide different event types
          # We store these options in activity_provider_options hash
          event_type = options.delete(:type) || self.name.underscore.pluralize

          options[:timestamp] ||= "#{table_name}.created_on"
          options[:find_options] ||= {}
          options[:author_key] = "#{table_name}.#{options[:author_key]}" if options[:author_key].is_a?(Symbol)
          self.activity_provider_options[event_type] = options
        end
      end

      module InstanceMethods
        def self.included(base)
          base.extend ClassMethods
        end

        module ClassMethods
          # Time 2015-01-27 16:30:47
          # Author lizanle
          # Description 用原来的写法from,to更加容易懂
          # Returns events of type event_type visible by user that occured between from and to
          def find_events(event_type, user, from, to, options)
            provider_options = activity_provider_options[event_type]
            raise "#{self.name} can not provide #{event_type} events." if provider_options.nil?

            scope = self



            if options[:author]
              return [] if provider_options[:author_key].nil?
              scope = scope.scoped(:conditions => ["#{provider_options[:author_key]} = ?", options[:author].id])
            end

            # add by nwb
            if options[:is_public]  && !provider_options[:is_public].nil?
              scope = scope.scoped(:conditions => ["#{provider_options[:is_public]} = ?", options[:is_public]])
            end

            if options[:limit]
              # id and creation time should be in same order in most cases
              scope = scope.scoped(:order => "#{table_name}.id DESC", :limit => options[:limit])
            end

            if provider_options.has_key?(:permission)
              if  options[:course]
                scope = scope.scoped(:conditions => Course.allowed_to_condition(user, provider_options[:permission] || :view_course, options))
              else
                scope = scope.scoped(:conditions => Project.allowed_to_condition(user, provider_options[:permission] || :view_project, options))
              end
            elsif respond_to?(:visible)
              if  options[:course]
                scope = scope.course_visible(user, options)
              else
                scope = scope.visible(user, options)
              end
            elsif options[:course]
              scope = scope.scoped(:conditions => Course.allowed_to_condition(user, "view_#{self.name.underscore.pluralize}".to_sym, options))
            else
              ActiveSupport::Deprecation.warn "acts_as_activity_provider with implicit :permission option is deprecated. Add a visible scope to the #{self.name} model or use explicit :permission option."
              scope = scope.scoped(:conditions => Project.allowed_to_condition(user, "view_#{self.name.underscore.pluralize}".to_sym, options))
            end
            # Time 2015-01-27 15:18:33
            # Author lizanle
            # Description 删除 unless scope.all，因为这个执行查询，并且没有加入时间限制，与下边 scope.all(provider_options[:find_options].dup)重复
            if options[:course]
              scope.all(provider_options[:find_options].dup)
            else
              if from && to
                scope = scope.scoped(:conditions => ["#{provider_options[:timestamp]} BETWEEN ? AND ?", from, to])
                scope.all(provider_options[:find_options].dup)
              end
            end
          end

          # 为了首页获取数据基本复制了上面的方法，改变了用户查看权限，增加了对讨论区的识别。
          # 因为新建了讨论区的内容，没有与项目方法混合，但是 event_type 取值类型还在共用，可能会对项目活动取值性能造成影响
          # 不过鉴于项目参与查询的条件减少，而增加的时间没有可见增长，重写event_type 的类型需要设计到lib，暂时不做改动
          def find_events1(event_type, user, from, to, options)
            provider_options = activity_provider_options[event_type]
            raise "#{self.name} can not provide #{event_type} events." if provider_options.nil?

            scope = self
            if from && to
              scope = scope.scoped(:conditions => ["#{provider_options[:timestamp]} BETWEEN ? AND ?", from, to])
            end

            if options[:author]
              return [] if provider_options[:author_key].nil?
              scope = scope.scoped(:conditions => ["#{provider_options[:author_key]} = ?", options[:author].id])
            end

            if options[:limit]
              # id and creation time should be in same order in most cases
              scope = scope.scoped(:order => "#{table_name}.id DESC", :limit => options[:limit])
            end

            user1 = User.find_by_admin(true)
            if  event_type.to_s == 'course_files' || event_type.to_s == 'course_journals_for_messages' || event_type.to_s == 'course_messages'
              scope = scope
            elsif provider_options.has_key?(:permission)
              scope = scope.scoped(:conditions => Project.allowed_to_condition(user1, provider_options[:permission] || :view_project, options))
            elsif respond_to?(:visible)
              scope = scope.visible(user1, options)
            elsif provider_options.has_key?(:func) && provider_options[:func].eql?('memos')
              scope = scope
            else
              ActiveSupport::Deprecation.warn "acts_as_activity_provider with implicit :permission option is deprecated. Add a visible scope to the #{self.name} model or use explicit :permission option."
              # scope = scope
              scope = scope.scoped(:conditions => Project.allowed_to_condition(user1, "view_#{self.name.underscore.pluralize}".to_sym, options))
            end
            scope.all(provider_options[:find_options].dup)
          end

        end
      end
    end
  end
end
