class Google::Sheets::Covid::ScreeningService < Google::Sheets::ApplicationService
  include DateRangeHelper

  def initialize(school, user, date_range, grades, classroom_ids)
    @school = school
    @date_range = date_range
    @grades = grades
    @classroom_ids = classroom_ids
    @label = 'Covid Screenings'
    super(user)
  end

  private
    def body
      data = []
      data << headers
      screenings.each { |s| data << s }
      data
    end

    def headers
      attributes = [
        'Date/Time',
        'Last Name',
        'First Name',
        'Grade',
        'DOB',
        'Age'
      ]
      attributes + questions.map(&:title)
    end

    def screenings
      @school.covid_screenings
        .includes(:student, answers: :options)
        .by_grades(@grades)
        .by_date_range(datetime_range(@date_range))
        .by_classroom(@classroom_ids)
        .map { |s| screening_props(s) }
    end

    def screening_props(screening)
      attributes = [
        screening.decorate.recorded_at,
        screening.student.last_name,
        screening.student.first_name,
        screening.student.decorate.grade_level,
        screening.student.decorate&.birth_date,
        screening.student.decorate.age
      ]
      attributes + questions.map do |question|
        answers = screening.answers.find { |a| a.question_id == question.id }
        if question.has_options?
          answers&.options&.map(&:value)&.join(' ')
        else
          answers&.value
        end
      end
    end

    def questions
      @questions ||= @school.covid_form_questions
        .by_employee_field(false)
        .order('covid_form_sections.sequence ASC', :sequence)
    end
end
