class Csv::EdFi::Indiana::GraduationPlansService < Csv::ApplicationService
  include EdFi::IndianaHelper

  def initialize(school_id)
    @school_id = school_id
  end

  def call
    CSV.generate do |csv|
      csv << headers
      students.each do |student|
        student.student.ed_fi_graduation_plans.each do |graduation_plan|
          csv << props(graduation_plan)
        end
      end
    end
  end

  private
    def school
      @school ||= School.find(@school_id)
    end

    def grades
      @grades ||= school.grades_hash
    end

    def students
      @students ||= school.current_year.school_year_students
        .preload(student: [:ed_fi_graduation_plans, :state_number])
        .joins(:student)
        .where(exit_date: [nil, 0, ''])
        .where.not(Students: { GradYear: [nil, '', 0] })
        .distinct
    end

    def headers
      [
        'Student Last Name',
        'Student First Name',
        'Student State ID',
        'Student Grade',
        'Graduation Year',
        'Plan',
        'Start date',
        'End date',
        'Alternate Plan'
      ]
    end

    def props(graduation_plan)
      student = graduation_plan.student
      [
        student.last_name,
        student.first_name,
        student.state_id,
        grades[student.grade],
        student.graduation_year,
        graduation_plan.plan_descriptor_name,
        graduation_plan.start_date,
        graduation_plan.end_date,
        graduation_plan.alternative_plan_descriptor_name
      ]
    end
end
