class Www::InformationRankingsController < WwwController

  def index

    if params[:information_standard_category_id].present?
      @information_standard_category = InformationStandardCategory.find params[:information_standard_category_id]
    else
      @information_standard_category = InformationStandardCategory.with_published_information_ranking.first
    end
    @information_standard_categories = InformationStandardCategory.with_published_information_ranking
    @institutions = @information_standard_category.institutions.where(ranked: true).order(:name)
    @information_standards = @information_standard_category.information_standards
    @information_rankings = @information_standard_category.information_rankings.where(published: true).order('closed_at desc')

    add_breadcrumb I18n.t('www.layout.home'), www_root_path
    add_breadcrumb t('www.information_rankings.index.title')
  end

  def get_rankings

    information_ranking = InformationRanking.find params[:information_ranking_id]
    institutions = Institution.find(params[:institution_ids], order: :name)
    information_standards = InformationStandard.find(params[:information_standard_ids], order: :name)

    headers = []
    information_standards.each do |information_standard|
      headers << information_standard.acronym if information_ranking.has_scores_for_standard?(information_standard)
    end

    results = []

    institutions.each do |institution|
      if information_ranking.has_scores_for_institution?(institution)
        result = []
        scores = []
        information_standards.each do |information_standard|
          if information_ranking.has_scores_for_standard?(information_standard)
            information_ranking_history = InformationRankingHistory.where(information_ranking_id: information_ranking.id, institution_id: institution.id, information_standard_id: information_standard.id).first

            if information_ranking_history.nil?
              scores << { info: '', score: 0 }
            else
              scores << { info: draw_information_standard_criteria(information_ranking_history, false), score: (information_ranking_history.score.to_f / 10) }
            end
          end
        end

        unless scores.map{ |score| score[:score] }.inject(:+).to_f == 0.0
          # average = scores.instance_eval { reduce(:+) / size.to_f }
          average = information_ranking.score_by_institution(institution).round(2)
          result << institution.acronym
          result += scores
          result << average.round(2)
          # Switch this when change the ranking
          # calification base
          # result << (average * 100 / 10).round
          # result << (average * 100 / 3).round
          results << result
        end
      end
    end

    results.sort_by!{ |e| -e.last }

    respond_to do |format|
      format.json { render json: { headers: headers, results: results } }
    end
  end

end
