require 'csv'

class Admission::ApplicantsCsv < ApplicationService
  def initialize(school, options)
    @school = school
    @school_year_id = options['admission_school_year_id']
    @application_id = set_value(options['admission_application_id'])
    @grade = set_value(options['applicant_grade'])
    @system_status = options['applicant_status_id']
    @returning = options['new_returning_students']
    @enrollment = options['enrollment'].to_bool
  end

  def call
    CSV.generate do |csv|
      csv << headers
      applicants.each do |applicant|
        csv << [
          applicant.first_name,
          applicant.last_name,
          applicant.birth_date,
          applicant.gender_label,
          applicant.grade,
          applicant.application.name,
          applicant.created_date,
          applicant.submission_date,
          applicant.family.name,
          applicant.system_status
        ]
      end
    end
  end

  private
    def school_year
      @school.school_years.find(@school_year_id)
    end

    def applicants
      school_year.admission_applicants
        .where(admission_applications: { enrollment: @enrollment })
        .with_application(@application_id)
        .with_grade(@grade)
        .with_system_status(@system_status)
        .with_returning(@returning)
        .includes(:family, :status)
        .references(:family, :status)
        .ordered
        .decorate
    end

    def headers
      [
        'Student First Name',
        'Student Last Name',
        'DOB',
        'Gender',
        'Application Grade',
        'Application Name',
        'Created Date',
        'Submitted Date',
        'Family Name',
        'Status'
      ]
    end

    def set_value(value)
      value == 'all' ? nil : value
    end
end
