# 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.

class FilesController < ApplicationController

    layout 'base_projects' #by young

  menu_item :files

  before_filter :find_project_by_project_id#, :except => [:getattachtype]
  before_filter :authorize, :except => [:getattachtype,:quote_resource_show,:search]

  helper :sort
  include SortHelper
  include FilesHelper
  helper :project_score
  include CoursesHelper

  def show_attachments obj
    @attachments = []
    obj.each do |container|
      @attachments += container.attachments
    end
    @all_attachments = visable_attachemnts(@attachments)
    @limit = 10
    @feedback_count = @all_attachments.count
    @feedback_pages = Paginator.new @feedback_count, @limit, params['page']
    @offset ||= @feedback_pages.offset
    @curse_attachments_all = @all_attachments[@offset, @limit]
    @curse_attachments = paginateHelper @all_attachments,10
  end

  def search
    sort = ""
    @sort = ""
    @order = ""
    @is_remote = true
    if params[:sort]
      order_by = params[:sort].split(":")
      @sort = order_by[0]
      if order_by.count > 1
        @order = order_by[1]
      end
      sort = "#{@sort} #{@order}"
    end

    begin
      q = "%#{params[:name].strip}%"
      #(redirect_to stores_url, :notice => l(:label_sumbit_empty);return) if params[:name].blank?
      if params[:insite]
        @result = find_public_attache q,sort
        @result = visable_attachemnts_insite @result,@course
        @searched_attach = paginateHelper @result,10
      else
        @result = find_course_attache q,@course,sort
        @result = visable_attachemnts @result
        @searched_attach = paginateHelper @result,10
      end

    #rescue Exception => e
    #  #render 'stores'
    #  redirect_to search_course_files_url
    end
  end

  def find_course_attache keywords,course,sort = ""
    if sort == ""
      sort =  "created_on DESC"
    end
    resultSet = Attachment.where("attachments.container_type = 'Course' And attachments.container_id = '#{course.id}' AND filename LIKE :like ", like: "%#{keywords}%").
        reorder(sort)
    #resultSet = Attachment.find_by_sql("SELECT `attachments`.* FROM `attachments` LEFT OUTER JOIN `homework_attaches` ON `attachments`.container_type = 'HomeworkAttach' AND `attachments`.container_id = `homework_attaches`.id LEFT OUTER JOIN `homework_for_courses` ON `homework_attaches`.bid_id = `homework_for_courses`.bid_id LEFT OUTER JOIN `homework_for_courses` AS H_C ON `attachments`.container_type = 'Bid' AND `attachments`.container_id = H_C.bid_id WHERE (`homework_for_courses`.course_id = 117 OR H_C.course_id = 117 OR (`attachments`.container_type = 'Course' AND `attachments`.container_id = 117)) AND `attachments`.filename LIKE '%#{keywords}%'").reorder("created_on DESC")
  end

  def find_public_attache keywords,sort = ""
    # StoresController#search 将每条文件都查出来，再次进行判断过滤。---> resultSet.to_a.map
    # 此时内容不多速度还可，但文件增长，每条判断多则进行3-4次表连接。
    # 现在还木有思路 药丸
    if sort == ""
      sort =  "created_on DESC"
    end
    resultSet = Attachment.where("attachments.container_type IS NOT NULL AND attachments.copy_from IS NULL AND filename LIKE :like ", like: "%#{keywords}%").
              reorder(sort)
  end

  def index
    #sort_init 'filename', 'asc'
    sort_init 'created_on', 'desc' 
    sort_update   'created_on' => "#{Attachment.table_name}.created_on", 
                  'filename' => "#{Attachment.table_name}.filename",
                  'size' => "#{Attachment.table_name}.filesize",
                  'downloads' => "#{Attachment.table_name}.downloads"
    sort = ""
    @sort = ""
    @order = ""
    @is_remote = false
    if params[:project_id]
      @isproject = true

      if params[:sort]
        params[:sort].split(",").each do |sort_type|
          order_by = sort_type.split(":")

          case order_by[0]
            when "filename"
              attribute = "filename"
            when "size"
              attribute = "filesize"
            when "attach_type"
              attribute = "attachtype"
            when "content_type"
              attribute = "created_on"
            when "field_file_dense"
              attribute = "is_public"
            when "downloads"
              attribute = "downloads"
            when "created_on"
              attribute = "created_on"
          end

          if order_by.count == 1
            sort += "#{Attachment.table_name}.#{attribute} asc " if attribute
          elsif order_by.count == 2
            sort += "#{Attachment.table_name}.#{attribute} #{order_by[1]} " if attribute && order_by[1]
          end
          if sort_type != params[:sort].split(",").last
            sort += ","
          end
        end
      end

      @containers = [ Project.includes(:attachments).reorder(sort).find(@project.id)]
      @containers += @project.versions.includes(:attachments).reorder(sort).all

      show_attachments @containers

      render :layout => !request.xhr?
    elsif params[:course_id]
      @isproject = false

      if params[:sort]
        params[:sort].split(",").each do |sort_type|
          order_by = sort_type.split(":")

          case order_by[0]
            when "filename"
              attribute = "filename"
            when "size"
              attribute = "filesize"
            when "attach_type"
              attribute = "attachtype"
            when "content_type"
              attribute = "created_on"
            when "field_file_dense"
              attribute = "is_public"
            when "downloads"
              attribute = "downloads"
            when "created_on"
              attribute = "created_on"
            when "quotes"
              attribute = "quotes"
          end
          @sort = order_by[0]
          @order = order_by[1]
          if order_by.count == 1 && attribute
            sort += "#{Attachment.table_name}.#{attribute} asc "
            if sort_type != params[:sort].split(",").last
              sort += ","
            end
          elsif order_by.count == 2 && order_by[1]
            sort += "#{Attachment.table_name}.#{attribute} #{order_by[1]} "
            if sort_type != params[:sort].split(",").last
              sort += ","
            end
          end
        end
      end

      @containers = [ Course.includes(:attachments).reorder(sort).find(@course.id)]

      show_attachments @containers

      render :layout => 'base_courses'
    end

  end

  def quote_resource_show
    @file = Attachment.find(params[:id])
    @can_quote = attachment_candown @file
  end

  def new
    @versions = @project.versions.sort
    @course_tag = @project.project_type
    if @project.project_type == 1
      render :layout => 'base_courses'
    end
  end

  def create
   if params[:add_tag]
     @addTag=true
     #render :back
      tag_saveEx
      #render :text =>"success"
      respond_to do |format|
       format.js
     end
   else
     #modify by nwb
     if @project
       @addTag=false
       container = (params[:version_id].blank? ? @project : @project.versions.find_by_id(params[:version_id]))
       attachments = Attachment.attach_filesex(container, params[:attachments], params[:attachment_type])
       render_attachment_warning_if_needed(container)

       if !attachments.empty? && !attachments[:files].blank? && Setting.notified_events.include?('file_added')
         Mailer.attachments_added(attachments[:files]).deliver
       end

       # TODO: 临时用 nyan
       sort_init 'created_on', 'desc'
       sort_update 'created_on' => "#{Attachment.table_name}.created_on",
                   'filename' => "#{Attachment.table_name}.filename",
                   'size' => "#{Attachment.table_name}.filesize",
                   'downloads' => "#{Attachment.table_name}.downloads"

       @containers = [Project.includes(:attachments).reorder("#{Attachment.table_name}.created_on DESC").find(@project.id)] #modify by Long Jun
       @containers += @project.versions.includes(:attachments).reorder("#{Attachment.table_name}.created_on DESC").all.sort

       show_attachments @containers

       @attachtype = 0
       @contenttype = 0

       respond_to do |format|
         format.js
         format.html {
           redirect_to project_files_url(@project)
         }
       end
     elsif @course
       @addTag=false
       attachments = Attachment.attach_filesex(@course, params[:attachments], params[:attachment_type])

       if !attachments.empty? && !attachments[:files].blank? && Setting.notified_events.include?('file_added')
         Mailer.attachments_added(attachments[:files]).deliver
       end

       # TODO: 临时用 nyan
       sort_init 'created_on', 'desc'
       sort_update 'created_on' => "#{Attachment.table_name}.created_on",
                   'filename' => "#{Attachment.table_name}.filename",
                   'size' => "#{Attachment.table_name}.filesize",
                   'downloads' => "#{Attachment.table_name}.downloads"

       @containers = [Course.includes(:attachments).reorder("#{Attachment.table_name}.created_on DESC").find(@course.id)]

       show_attachments @containers

       @attachtype = 0
       @contenttype = 0

       respond_to do |format|
         format.js
         format.html {
           redirect_to course_files_url(@course)
         }
       end
     end

   end
  end

  def tag_saveEx
    @tags = params[:tag_name][:name]
    @obj_id = params[:object_id]
    @obj_flag = params[:object_flag]

    case @obj_flag
      when '1' then
        @obj = User.find_by_id(@obj_id)
      when '2' then
        @obj = Project.find_by_id(@obj_id)
      when '3' then
        @obj = Issue.find_by_id(@obj_id)
      when '4' then
        @obj = Bid.find_by_id(@obj_id)
      when '5' then
        @obj = Forum.find_by_id(@obj_id)
      when '6'
        @obj = Attachment.find_by_id(@obj_id)
      when '7' then
        @obj = Contest.find_by_id(@obj_id)
      when '8'
        @obj = OpenSourceProject.find_by_id(@obj_id)
      when '9'
        @obj = Course.find_by_id(@obj_id)
      else
        @obj = nil
    end
    unless @obj.nil?
      @obj.tag_list.add(@tags.split(","))
    else
      return
    end
    if @obj.save
      ## 执行成功的操作。
    else
      #捕获异常
    end
   end

  # 返回指定资源类型的资源列表
  # added by nwb
  def getattachtype
    sort_init 'created_on', 'desc' 
    sort_update   'created_on' => "#{Attachment.table_name}.created_on", 
                  'filename' => "#{Attachment.table_name}.filename",
                  'size' => "#{Attachment.table_name}.filesize",
                  'downloads' => "#{Attachment.table_name}.downloads"
    sort=''

    if params[:sort]
      params[:sort].split(",").each do |sort_type|
        order_by = sort_type.split(":")

        case order_by[0]
          when "filename"
            attribute = "filename"
          when "size"
            attribute = "filesize"
          when "attach_type"
            attribute = "attachtype"
          when "content_type"
            attribute = "created_on"
          when "field_file_dense"
            attribute = "is_public"
          when "downloads"
            attribute = "downloads"
          when "created_on"
            attribute = "created_on"
        end

        if order_by.count == 1
          sort += "#{Attachment.table_name}.#{attribute} asc "
        elsif order_by.count == 2
          sort += "#{Attachment.table_name}.#{attribute} #{order_by[1]} "
        end
        if sort_type != params[:sort].split(",").last
          sort += ","
        end
      end
    end

   if @project
     @isproject = true
     @containers = [ Project.includes(:attachments).reorder("#{Attachment.table_name}.created_on DESC").find(@project.id)]
     @containers += @project.versions.includes(:attachments).reorder(sort).all
     show_attachments @containers
     @attachtype = params[:type].to_i
     @contenttype = params[:contentType].to_s
      respond_to do |format|
        format.js
       format.html {
         render :layout => 'base_projects'
       }
      end

   elsif @course
      @isproject = false
      @containers = [ Course.includes(:attachments).reorder(sort).find(@course.id)]
      show_attachments @containers
      @attachtype = params[:type].to_i
      @contenttype = params[:contentType].to_s
     # render layout:  'base_courses'
      respond_to do |format|
        format.js
        format.html {
          render :layout => 'base_courses'
        }
      end
   else
     show_attachments @containers
     @attachtype = params[:type].to_i
     @contenttype = params[:contentType].to_s

     respond_to do |format|
        format.js
        format.html
     end
   end



  end
end
