#  fq
# class BidsController < ApplicationController
class ContestsController < ApplicationController
  menu_item :respond                
  menu_item :project, :only => :show_project
  menu_item :application, :only => :show_softapplication
  before_filter :find_contest, :only => [:show_contest, :show_project, :show_softapplication, :create,:destroy,:more,:back,:add,:add_softapplication,:new,:show_results, :set_reward,
                :show_contest_project, :show_contest_user, :join_in_contest, :unjoin_in_contest, :new_join,:show_participator, :settings]
              
  # added by fq
  before_filter :require_login, :only => [:join_in_contest, :unjoin_in_contest]
  # end
  before_filter :require_login,:only => [:set_reward, :destroy, :add, :new, ]

  helper :watchers
  helper :attachments
  include AttachmentsHelper
  include ApplicationHelper
  helper :projects
  helper :words


  def index
    # @contests = Contest.visible
    # @contests ||= []
    @offset, @limit = api_offset_and_limit({:limit => 10})
    @contests = Contest.visible    
    @contests = @contests.like(params[:name]) if params[:name].present?
    @contest_count = @contests.count
    @contest_pages = Paginator.new @contest_count, @limit, params['page']

    @offset ||= @contest_pages.reverse_offset
    if params[:contest_sort_type].present?
    case params[:contest_sort_type]
      when '0'
        unless @offset == 0
          @contests = @contests.reorder('contests.commit').offset(@offset).limit(@limit).all.reverse
        else
          limit = @contest_count % @limit
          limit = @limit  if limit == 0
          @contests = @contests.reorder('contests.commit').offset(@offset).limit(limit).all.reverse
        end
        @s_state = 0
      when '1'
        unless @offset == 0
          @contests = @contests.reorder('contests.created_on').offset(@offset).limit(@limit).all.reverse
        else
          limit = @contest_count % @limit
          limit = @limit  if limit == 0
          @contests = @contests.reorder('contests.created_on').offset(@offset).limit(limit).all.reverse
        end
        @s_state = 1
      when '2'
        unless @offset == 0
          @contests = @contests.offset(@offset).limit(@limit).all.reverse
        else
          limit = @contest_count % @limit
          limit = @limit  if limit == 0
          @contests = @contests.offset(@offset).limit(@limit).all.reverse
        end
        @s_state = 0
      end
      else
        unless @offset == 0
          @contests = @contests.reorder('contests.created_on').offset(@offset).limit(@limit).all.reverse
        else
          limit = @contest_count % @limit
          limit = @limit  if limit == 0
          @contests = @contests.reorder('contests.created_on').offset(@offset).limit(limit).all.reverse
        end
        @s_state = 1
    end
  end

  def show_contest
    @user = @contest.author
    @jours = @contest.journals_for_messages.where('m_parent_id IS NULL').order('created_on DESC')
    @limit =  10
    @feedback_count = @jours.count
    @feedback_pages = Paginator.new @feedback_count, @limit, params['page']
    @offset ||= @feedback_pages.offset
    @jour = @jours[@offset, @limit]
    @state = false

    respond_to do |format|
      layout_file = 'base_newcontest'
      format.html {
        render :layout => layout_file
      }
      format.api
    end
  end
  
  def join_in_contest
    if params[:contest_password] == @contest.password
      JoinInCompetition.create(:user_id => User.current.id, :competition_id => @contest.id)
      @state = 0
    else
      @state = 1
    end
 
    respond_to do |format|
      format.js { render :partial => 'set_join', :locals => {:user => User.current, :object_id => params[:id]} }
    end
  end
  
  def unjoin_in_contest
     
    joined = JoinInCompetition.where('competition_id = ? and user_id = ?', @contest.id, User.current.id)
            
    joined.each do |join|
      join.delete
    end
    
    respond_to do |format|
      format.js { render :partial => 'set_join', :locals => {:user => User.current, :object_id => params[:id]} }
    end
  end
  
  def new_join


  end
  
  def show_participator
    render :layout => 'base_newcontest'
    
  end
  
  
  def settings
     if @contest.author.id == User.current.id 
           @contest = Contest.find(params[:id])
           render :layout => 'base_newcontest'
     else
         render_403 :message => :notice_not_contest_setting_authorized
     end
  end

  # Added by Longjun
  def destroy_contest
    @contest = Contest.find(params[:id])
    if @contest.author_id == User.current.id
      
      @contest.destroy
      redirect_to action: 'index'
    else
      render_403 :message => :notice_not_contest_delete_authorized
    end
    
  end
  # end
  
  def show_contest_project
    contests = Contest.where('parent_id = ?', @contest.id)
    @projects = []
    for contest in contests
      @projects += contest.contesting_projects
    end

    respond_to do |format|
        format.html {
          render :layout => 'base_newcontest'
        }
        format.api

    end
  end

  def show_contest_softapplication
    contests = Contest.where('parent_id = ?', @contest.id)
    @softapplications = []
    for contest in contests
      @softapplications += contest.contesting_softapplications
    end

    respond_to do |format|
        format.html {
          render :layout => 'base_newcontest'
        }
        format.api

    end
  end
  
  def show_contest_user
    contests = Contest.find(:all)
    @users = []
    for contest in contests
      for project in contest.projects
        @users += project.users
      end
    end

    respond_to do |format|
        format.html {
          render :layout => 'base_newcontest'
        }
        format.api

    end
  end
  #显示参赛的项目
  def show_project
    @membership = User.current.memberships.all(:conditions => Project.visible_condition(User.current))
    @option = []
    # @contesting_project_count = @contesting_project_all.count
    # @contesting_project_pages = Paginator.new @contesting_project_count, per_page_option, params['page']
    @membership.each do |membership|
      unless(membership.project.project_type==1)
        membership.member_roles.each{|role|
          if(role.role_id == 3)
          @option << membership.project
          end
        }
      end
    end
    @user = @contest.author
    @contesting_project = @contest.contesting_projects.all
    if params[:student_id].present?
      @temp = []
      @contesting_project.each do |pro|
        if pro.project && pro.project.project_status
          if /#{params[:student_id]}/ =~  pro.user.user_extensions.student_id
            @temp << pro
          end
        end
        @temp
      end
      @contesting_project = @temp
    else
  
      @temp = []
      @contesting_project.each do |pro|
        if pro.project && pro.project.project_status
          @temp << pro
        end
        @temp
      end
      if @temp.size > 0
          @contesting_project = @temp.sort {|a,b| b.project.project_status.grade <=> a.project.project_status.grade}
      end
    end
    @contesting_project = paginateHelper @contesting_project
    respond_to do |format|
      format.html {
        render :layout => 'base_newcontest'
      }     
      format.api
    end
  end 
  ############
  ##显示参赛的应用
  def show_softapplication
    # @membership = User.current.memberships.all(:conditions => Project.visible_condition(User.current))
    # @option = []  

    # @user = @contest.user
    @softapplication = Softapplication.all 
    @contesting_softapplication = @contest.contesting_softapplications

    @contesting_softapplication = paginateHelper  @contesting_softapplication, 10
    
    # @temp = []
    # @softapplicationt.each do |pro|
    #   if pro.project && pro.project.project_status
    #     @temp << pro
    #   end
    #   @temp
  
    # if @temp.size > 0
    #     @contesting_project = @temp.sort {|a,b| b.project.project_status.grade <=> a.project.project_status.grade}
    # end
    # end
    # respond_to do |format|
    #   format.html {
    #     render :layout => 'base_newcontest'
    #   }     
    #   format.api
    # end  
##########################
    @contest = Contest.find_by_id(params[:id])
    respond_to do |format|
      format.html {
        render :layout => 'base_newcontest'
      }     
      format.api
    end
  end
 
  ###添加已创建的参赛项目
  def add
    project = Project.find(params[:contest])
    contest_message = params[:contest_for_save][:contest_message]
    if ContestingProject.where("project_id = ? and contest_id = ?", project.id, @contest.id).size == 0
      if ContestingProject.cerate_contesting(@contest.id, project.id, contest_message)
        flash.now[:notice] = l(:label_bidding_contest_succeed)
      end
    else
      flash.now[:error] = l(:label_bidding_fail)
    end
    
    @contesting_project = paginateHelper @contest.contesting_projects
    
    respond_to do |format|

      format.html { redirect_to :back }
      format.js
    end
  end
  ###添加已发布的参赛应用
  def add_softapplication
    softapplication = Softapplication.find(params[:contest])
    contest_message = params[:contest_for_save][:contest_message]
    if ContestingSoftapplication.where("softapplication_id = ? and contest_id = ?", softapplication.id, @contest.id).size == 0
      if ContestingSoftapplication.create_softapplication_contesting(@contest.id, softapplication.id, contest_message)
        flash.now[:notice] = l(:label_release_add_contest_succeed)
      end
    else
      flash.now[:error] = l(:label_add_contest_succeed_fail)
    end
    
    @contesting_softapplication = paginateHelper @contest.contesting_softapplications
    
    respond_to do |format|

      format.html { redirect_to :back }
      format.js
    end
  end
  ## 新建留言
  def create

    if params[:contest_message][:message].size>0
      if params[:reference_content]
        message = params[:contest_message][:message] + "\n" + params[:reference_content]
      else
        message = params[:contest_message][:message]
      end
      refer_user_id = params[:contest_message][:reference_user_id].to_i
      @contest.add_jour(User.current, message, refer_user_id)
    end
    @user = @contest.author
    @jours = @contest.journals_for_messages.where('m_parent_id IS NULL').order('created_on DESC')
    @limit =  10
    @feedback_count = @jours.count
    @feedback_pages = Paginator.new @feedback_count, @limit, params['page']
    @offset ||= @feedback_pages.offset
    @jour = @jours[@offset, @limit]
    @contest.set_commit(@feedback_count)

    respond_to do |format|
      format.js
    end

  end

  ##删除留言
  def destroy
    @user = @contest.author
    if User.current.admin? || User.current.id == @user.id
      JournalsForMessage.delete_message(params[:object_id])
    end
    @jours = @contest.journals_for_messages.reverse
    @limit =  10
    @feedback_count = @jours.count
    @feedback_pages = Paginator.new @feedback_count, @limit, params['page']
    @offset ||= @feedback_pages.offset
    @jour = @jours[@offset, @limit]

    @contest.set_commit(@feedback_count)
    respond_to do |format|
      format.js
    end
  end

  ##引用留言
  def new
    @jour = JournalsForMessage.find(params[:journal_id]) if params[:journal_id]
    if @jour
      user = @jour.user
      text = @jour.notes
    else
      user = @contest.author
      text = @contest.description
    end
    text = text.to_s.strip.gsub(%r{<pre>((.|\s)*?)</pre>}m, '[...]')
    @content = "> #{ll(User.current.language, :text_user_wrote, user)}\n> "
    @content << text.gsub(/(\r?\n|\r\n?)/, "\n> ") + "\n\n"
    @id = user.id
    rescue ActiveRecord::RecordNotFound
    render_404
  end

  ##新建竞赛
  def new_contest
    @contest = Contest.new
    @contest.safe_attributes = params[:contest]
  end
  
  ##提交创建的竞赛
  def create_contest
    @contest = Contest.new
    @contest.name = params[:contest][:name]
    @contest.description = params[:contest][:description]
    @contest.budget = params[:contest][:budget]
    @contest.deadline = params[:contest][:deadline]
    @contest.password = params[:contest][:password]     
    @contest.author_id = User.current.id
    @contest.commit = 0
    if @contest.save
      unless @contest.watched_by?(User.current)
        if @contest.add_watcher(User.current)
          flash[:notice] = l(:label_contesting_created_succeed)
        end
      end
      redirect_to show_contest_contest_path(@contest)
    else
      @contest.safe_attributes = params[:contest]
      render :action => 'new_contest'
    end
  end

  ##更新竞赛配置信息
  def update_contest
    @contest = Contest.find(params[:id])
    @contest.name = params[:contest][:name]
    @contest.description = params[:contest][:description]
 
    @contest.budget = params[:contest][:budget]
    @contest.deadline = params[:contest][:deadline]
    @contest.password = params[:contest][:password]      
    @contest.author_id = User.current.id
    @contest.commit = 0
    if @contest.save
      unless @contest.watched_by?(User.current)
        if @contest.add_watcher(User.current)
          flash[:notice] = l(:label_contesting_updated_succeed)
        end
      end
      redirect_to show_contest_contest_path(@contest)
      
    else
      @contest.safe_attributes = params[:contest]
      render :action => 'new_contest'
    end
  end

  def more
    @jour = @contest.journals_for_messages
    @jour.each_with_index {|j,i| j.indice = i+1}
    @state = true

    respond_to do |format|
      format.html { redirect_to :back }
      format.js
    #format.api { render_api_ok }
    end
  end

  def back
    @jour = @contest.journals_for_messages
    @jour.each_with_index {|j,i| j.indice = i+1}
    @state = false

    respond_to do |format|
      format.html { redirect_to :back }
      format.js
    #format.api { render_api_ok }
    end
  end

  def set_reward
    @b_p = nil
    @contesting_project_id = nil

    if params[:set_reward][:reward]&&((User.current.id==@contest.author_id)||User.current.admin)
      # @contest_id = params[:id]
      @contesting_project_id = params[:set_reward][:b_id]   #[:b_id]???
      @b_p = ContestingProject.find_by_id(@contesting_project_id)

      # 把字段存进表中
      @b_p.update_reward(params[:set_reward][:reward].to_s)
    end

    respond_to do |format|
      format.js
    end
  end


  def manage

  end

  private

  def find_contest
    if params[:id]
      @contest = Contest.find(params[:id])
      @user = @contest.author
    end
  rescue
    render_404
    end

end

