# frozen_string_literal: true
module Panel
  #
  class InstitutionCalendarsController < PanelController
    include Panel::Crud
    include Panel::Multiple
    load_and_authorize_resource class_name: InstitutionCalendar


    def model
      InstitutionCalendar
    end


    def index
      respond_to do |format|
        format.html { super }
        format.csv  { super }
        format.json { respond_to_json }
      end
    end

    def show
      @institution_calendar = InstitutionCalendar.find(params[:id])
      @events = CalendarEvent.joins(:institution_calendar)
      .where('institution_calendars.institution_id = ?',
      @institution_calendar.institution_id)
      @events_by_date = @events.group_by{|u| u.start_at.to_date}
      @date = params[:date] ? Date.parse(params[:date]) : Date.current
      breadcrumbs_for(:show)
      respond_to do |format|
        format.html { }
        format.json {
          @list = @events.map do |e|
            { :id => e.id, :title => e.name,
              :start => e.start_at.strftime("%Y-%m-%d"),
              :end => e.end_at.blank? ? e.start_at.strftime("%Y-%m-%d") : e.end_at.strftime("%Y-%m-%d"),
              :url=>edit_panel_institution_calendar_calendar_event_url(@institution_calendar.id, e.id) }
          end
          @event_list = @list.to_json
          render json: @event_list
        }
      end
    end

    def respond_to_json
      @q = model.ransack(params[:filter])
      @c = @q.result.paginate(page: params[:page], per_page: params[:count])

      render json: json_result(@c)
    end

    def respond_to_html
      add_breadcrumb t('home'), panel_root_url
      add_breadcrumb humanized_model_name(:many), index_url
      render template: 'panel/institution_calendars/index'
    end

    def permits
      [:name]
    end

    def exportable_fields
      [:name]
    end

  end
end
