class Cooperative::CompetitionsController < Cooperative::BaseController
  before_action :find_competition, except: [:index]

  def index
    # params[:sort_by] = params[:sort_by].presence || 'created_at'
    # params[:sort_direction] = params[:sort_direction].presence || 'desc'
    @competitions = current_laboratory.competitions.order("created_at desc")
    @params_page = params[:page] || 1
    @competitions = paginate @competitions
    ids = @competitions.map(&:id)
    @member_count_map = TeamMember.where(competition_id: ids).group(:competition_id).count

    @competition_hot = ModuleSetting.exists?(module_type: "Competition", property: "hot")
    respond_to do |format|
      format.js
      format.html
    end
  end

  def create
    name = params[:competition_name].to_s.strip
    Competition.create!(name: name)
    render_ok
  end

  def hot_setting
    if params[:hot].to_i == 1 && !ModuleSetting.exists?(module_type: "Competition", property: "hot")
      ModuleSetting.create!(module_type: "Competition", property: "hot")
    elsif params[:hot].to_i == 0 && ModuleSetting.exists?(module_type: "Competition", property: "hot")
      ModuleSetting.where(module_type: "Competition", property: "hot").destroy_all
    end
    render_ok
  end

  def publish
    @competition.update_attributes!(published_at: Time.now)
  end

  def unpublish
    @competition.update_attributes!(published_at: nil)
  end

  def online_switch
    if @competition.status
      @competition.update_attributes!(status: false)
    else
      @competition.update_attributes!(status: true, online_time: Time.now)
    end
  end

  private

  def find_competition
    @competition = current_laboratory.competitions.find_by(id: params[:id])
  end

end