class Www::AccountabilitiesController < WwwController
  before_filter :build_breadcrumb, :general_vars

  def index
    year = params[:year].nil? ? (Date.today < Date.new(Date.today.year,6,1) ? Date.today.year-1 : Date.today.year) : params[:year]
    @accountability = RcAccountabilityResource.where(year: year).first rescue nil
    #@accountability = RcAccountabilityResource.last
    @citizen_evaluations = @accountability.rc_accountability_citizen_evaluations.order("score DESC").limit(4) rescue nil
    @spta_evaluations = @accountability.rc_accountability_spta_evaluations.sort_by(&:average_score).reverse rescue nil
    @spta_full_evaluations ||= []
    @gallery = @accountability.rc_accountability_photos rescue nil
    #Calendario
    @start_at = Date.parse(params[:start_at]) rescue Date.current 
    @end_at = @start_at + 10.days
    @events = InstitutionEvent.includes(:institution).active.order(:start_at).search({start_at_gteq: @start_at, start_at_lt: @end_at + 1.day}).result
    @events = @events.group_by{|event| event.start_at.to_date}
  end

  def citizen_evaluations
    @accountability = RcAccountabilityResource.find(params[:id])
    @q = @accountability.rc_accountability_citizen_evaluations.order("score DESC").search(params[:q])
    @citizen_evaluations = @q.result
    #@citizen_evaluations = @accountability.rc_accountability_citizen_evaluations.order("score DESC")
  end

  def institution_evaluations
    @accountability = RcAccountabilityResource.find(params[:id])
    @q = @accountability.rc_accountability_spta_evaluations.search(params[:q])
    @spta_evaluations = @q.result.sort_by(&:average_score).reverse
    #@citizen_evaluations = @accountability.rc_accountability_citizen_evaluations.order("score DESC")
  end

  private
  
  def build_breadcrumb
    add_breadcrumb I18n.t('www.layout.home'), www_root_path
    add_breadcrumb "Rendicion de cuentas", www_accountabilities_url
    add_breadcrumb "Evaluaciones ciudadanas" if params[:action].to_s == "citizen_evaluations"
    add_breadcrumb "Evaluaciones institucionales" if params[:action].to_s == "institution_evaluations"
  end

  def general_vars
    @applications_category = Page.find 7 
    @page = Page.find 6 #Transparencia
    @side_menu = []
    @side_menu << (@page.page_id.nil? ? @page : Page.find(@page.page_id))
    @side_menu << @page.pages.where(active: true).order("id ASC") rescue nil
    @side_menu = @side_menu.flatten
  end

=begin
  def index
    @q = Accountability.order(:event_day).includes(accountable: [city: :state]).search(params[:q])
    @q.event_day_gteq = Date.current unless params[:q]
    @accountabilities = @q.result.paginate(page: params[:page], per_page: 30)
    add_breadcrumb I18n.t('www.layout.home'), www_root_path
    add_breadcrumb I18n.t('www.applicatives.index.accountabilities')
  end

  def show
  end

  private
    def accountability
      @accountability ||= Accountability.find(params[:id])
    end
    helper_method :accountability
=end
end
