# encoding: utf-8
#
# 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 AttachmentsHelper
  # Displays view/delete links to the attachments of the given object
  # Options:
  #   :author -- author names are not displayed if set to false
  #   :thumbails -- display thumbnails if enabled in settings
  
  include Redmine::Pagination
  
  def link_to_attachments(container, options = {})
    options.assert_valid_keys(:author, :thumbnails)

    if container.attachments.any?
      options = {:deletable => container.attachments_deletable?, :author => true}.merge(options)
      render :partial => 'attachments/links',
        :locals => {:attachments => container.attachments, :options => options, :thumbnails => (options[:thumbnails] && Setting.thumbnails_enabled?)}
    end
  end

  def link_to_attachment_project(container, options = {})
    options.assert_valid_keys(:author, :thumbnails)

    if container.attachments.any?
      options = {:deletable => container.attachments_deletable?, :author => true}.merge(options)
      render :partial => 'attachments/project_file_links',
             :locals => {:attachments => container.attachments, :options => options, :thumbnails => (options[:thumbnails] && Setting.thumbnails_enabled?)}
    end
  end

  def link_to_attachments_course(container, options = {})
    options.assert_valid_keys(:author, :thumbnails)

    if container.attachments.any?
      options = {:deletable => container.attachments_deletable?, :author => true}.merge(options)
      render :partial => 'attachments/course_file_links',
             :locals => {:attachments => container.attachments, :options => options, :thumbnails => (options[:thumbnails] && Setting.thumbnails_enabled?)}
    end
  end
  
  def attach_delete(project)
    if User.current.logged? && (User.current.admin? || (!Member.where('user_id = ? and project_id = ?', User.current.id, project.bid.courses.first.id).first.nil? && (Member.where('user_id = ? and project_id = ?', User.current.id, project.bid.courses.first.id).first.roles&Role.where('id = ? or id = ?', 3, 7)).size >0) || project.user_id == User.current.id)
      true
    else
      false
    end

  end

  def render_api_attachment(attachment, api)
    api.attachment do
      api.id attachment.id
      api.filename attachment.filename
      api.filesize attachment.filesize
      api.content_type attachment.content_type
      api.description attachment.description
      api.content_url url_for(:controller => 'attachments', :action => 'download', :id => attachment, :filename => attachment.filename, :only_path => false)
      api.author(:id => attachment.author.id, :name => attachment.author.name) if attachment.author
      api.created_on attachment.created_on
    end
  end

  def link_to_memo_attachments(container, options = {})
    options.assert_valid_keys(:author, :thumbnails)

    if container.attachments.any?
      options = {:deletable => deletable?(container), :author => true}.merge(options)
      render :partial => 'attachments/links',
        :locals => {:attachments => container.attachments, :options => options, :thumbnails => (options[:thumbnails] && Setting.thumbnails_enabled?)}
    end
  end

  #判断课程course中是否包含课件attachment，course中引用了attachment也算作包含
  def course_contains_attachment? course,attachment
     course.attachments.each do |att|
       if att.id == attachment.id || (!att.copy_from.nil? && !attachment.copy_from.nil? && att.copy_from == attachment.copy_from) || att.copy_from == attachment.id || att.id == attachment.copy_from
         return true
      end
     end
     false
  end

  #判断项目project中是否包含课件attachment，project中引用了attachment也算作包含
  def project_contains_attachment? project,attachment
    project.attachments.each do |att|
      if att.id == attachment.id || (!att.copy_from.nil? && !attachment.copy_from.nil? && att.copy_from == attachment.copy_from) || att.copy_from == attachment.id || att.id == attachment.copy_from
        return true
      end
    end
    false
  end

  def get_qute_number attachment
    if attachment.copy_from
      result = Attachment.find_by_sql("select count(*) as number from attachments where copy_from = #{attachment.copy_from}")
    else
      result = Attachment.find_by_sql("select count(*) as number from attachments where copy_from = #{attachment.id}")
    end
    if result.nil? || result.count <= 0
      return 0
    else
      return result[0].number
    end
  end

  private

  def deletable? container, user=User.current
    User.current.logged? && (container.author == user || user.admin?)
  end
  
  # this method is used to get all projects that tagged one tag
  # added by william
  def get_attachments_by_tag(tag_name)
    Attachment.tagged_with(tag_name).order('created_on desc')
  end

  # this method is used to get all attachments that from one project and tagged one tag
  # added by Long Jun
   def get_attachments_by_project_tag(tag_name, obj)
     @project_id =nil
     if obj.container_type == 'Version'
         @project_id = Version.find(obj.container_id).project_id
       
    elsif obj.container_type == 'Project'
        @project_id = obj.container_id
       
     end
      attachments = Attachment.tagged_with(tag_name).order('created_on desc').where("(container_id = :project_id and container_type = 'Project') or
            (container_id in (select id from versions where project_id =:project_id) and container_type = 'Version')", {:project_id => @project_id})
     return attachments
  end


  def render_attachments_for_new_project(project, limit=nil)
    # 查询条件
    params[:q] ||= "" 
    filename_condition = params[:q].strip

    attachAll = Attachment.scoped
    # 当前项目所有资源
    # attachments = Attachment.find_all_by_container_type_and_container_id(project.class, project.id)
    # attachments = Attachment.where("container_type = '#{project.class}' and container_id = #{project.id}")

    # 除去当前项目的所有资源
    nobelong_attach = Attachment.where("!(container_type = '#{project.class}' and container_id = #{project.id})") unless project.blank?

    # 搜索域确定
    domain = project.nil? ? attachAll : nobelong_attach

    # 搜索到的资源
    searched_attach = domain.where("is_public=1 and filename LIKE :like ", like:"%#{filename_condition}%").limit(limit).order('created_on desc')
    #searched_attach = private_filter searched_attach
    searched_attach = paginateHelper(searched_attach, 10)

    s = content_tag('div', attachments_check_box_tags('attachment[attach][]', searched_attach), :id => 'attachments')
    links = pagination_links_full(@obj_pages, @obj_count, :per_page_links => false) {|text, parameters, options|
      link_to text, attachments_autocomplete_path( parameters.merge(:project_id=>project.id,:q => params[:q], :format => 'js')), :remote => true }

    return s + content_tag('div', content_tag('ul', links), :class => 'pagination')

    # ================================================================================================

    # attach_count = searched_attach.count
    # attach_pages = Redmine::Pagination::Paginator.new attach_count, 10, params['page'] #by young
    # attachs = searched_attach.offset(attach_pages.offset).limit(attach_pages.per_page).all

    # s = content_tag('div', attachments_check_box_tags('attachment[attach][]', attachs), :id => 'attachments')
    # links = pagination_links_full(attach_pages, attach_count, :per_page_links => false) {|text, parameters, options|
    #   link_to text, attachments_autocomplete_path( parameters.merge(:q => params[:q], :format => 'js')), :remote => true }

    # return s + content_tag('div', content_tag('ul', links), :class => 'pagination')
    # return searched_attach.to_json
  end

  # add by nwb
  def render_attachments_for_new_course(course, limit=nil)
    # 查询条件
    params[:q] ||= ""
    filename_condition = params[:q].strip

    #attachAll = Attachment.where("author_id = #{User.current.id}")
    #
    ## 除去当前课程的所有资源
    #nobelong_attach =

    # 搜索域确定
    course.nil? ?
        domain=Attachment.where("author_id = #{User.current.id}")
    :
        domain=Attachment.where("author_id = #{User.current.id} and container_type = 'Course' and container_id <> #{course.id}") unless course.blank?

    # 搜索到的资源
    searched_attach = domain.where("filename LIKE :like ", like:"%#{filename_condition}%").limit(limit).order('created_on desc')
    #searched_attach = private_filter searched_attach
    searched_attach = paginateHelper(searched_attach, 10)

    #testattach = Attachment.public_attachments

    s = content_tag('div', attachments_check_box_tags('attachment[attach][]', searched_attach), :id => 'attachments')
    links = pagination_links_full(@obj_pages, @obj_count, :per_page_links => false) {|text, parameters, options|
      link_to text, attachments_autocomplete_path( parameters.merge(:course_id=>course.id,:q => params[:q], :format => 'js')), :remote => true }

    return s + content_tag('div', content_tag('ul', links), :class => 'pagination')

  end

  def attachments_check_box_tags(name, attachs)
    s = ''
    attachs.each do |attach|
      s << "<label>#{ check_box_tag name, attach.id, false, :id => nil } #{h attach.filename}</label><br/>"
    end
    s.html_safe
  end



  # Modified by Longjun
  # 有参数的方法要加()
  def private_filter(resultSet)
    result = resultSet.to_a.dup

    # modify by nwb
    #添加对课程资源文件的判断
    resultSet.map { |res|
      if(res.container.nil? || 
        (res.container.class.to_s=="Project" && res.container.is_public == false) ||
        (res.container.has_attribute?(:project) && res.container.project && res.container.project.is_public == false) ||
        (res.container.class.to_s=="HomeworkAttach" && res.container.bid.reward_type == 3) ||
          (res.container.class.to_s=="Course" && res.container.is_public == false) ||
          (res.container.has_attribute?(:course) && res.container.course && res.container.course.is_public == false)
        )
        result.delete(res)
      end
    }
    result
  end

  # Modified by Longjun
  # include 应放在class/model 的开始处
  # include Redmine::Pagination
  # end
  
  def paginateHelper (obj, pre_size=10)
    @obj_count = obj.count
    @obj_pages = Paginator.new @obj_count, pre_size, params['page']
    if obj.kind_of? ActiveRecord::Base or obj.kind_of?  ActiveRecord::Relation
      obj.limit(@obj_pages.per_page).offset(@obj_pages.offset)
    elsif obj.kind_of? Array
      obj[@obj_pages.offset, @obj_pages.per_page]
    else
      logger.error "[ApplicationController] Error : application_controller#paginateHelper ===> unknow category: #{obj.class}"
      raise RuntimeError, 'unknow type, Please input you type into this helper.'
    end
  end

end
