class Admin::Legacy::StudentsController < ApplicationController
  def index
    data = students
      .join_school_year_student(params[:school_year_id], params[:status]&.to_sym)
      .by_grade(params[:grade])
      .by_categories(params[:category_ids])
      .distinct
      .ordered
      .pluck(:id, :first_name, :last_name, :code, :grade)
      .map do |id, first, last, code, grade|
        first, last = encode_strings_to_utf8([first, last])
        enrollment_grade = enrollment_by_student[id]&.grade_id || grade
        {
          id: id,
          full_name: "#{last}, #{first}",
          code: code,
          grade_label: grade_levels[enrollment_grade],
          grade: enrollment_grade
        }
      end

    render_success :ok, json: data
  end

  def show
    render_success :ok, json: student_props(student)
  end

  def update
    if student.update(student_params)
      render_success :ok, json: student_props(student.reload)
    else
      render_error :unprocessable_entity, errors: student
    end
  end

  def create_user
    user = student.build_user
    if user.save
      render_success :ok, message: 'User created.', json: student_props(student.reload)
    else
      render_error :unprocessable_entity, errors: user
    end
  end

  def available_codes
    render_success :ok, json: student.available_codes
  end

  private
    def school_year
      current_school.school_years.find_by(id: params[:school_year_id]) || current_school_year
    end

    def enrollment_by_student
      @enrollment_by_student ||= school_year.school_year_students.index_by(&:student_id)
    end

    def language_label(id)
      if current_school.ed_fi_system_indiana?
        EdFi::Descriptor.by_language_descriptor(current_school).find_by(key: id)&.name
      else
        current_school.languages.find_by(id: id)&.name
      end
    end

    def student_params
      params.permit(
        :first_name,
        :middle_name,
        :last_name,
        :suffix,
        :graduated,
        :graduation_year,
        :graduation_month,
        :graduation_day,
        :code,
        :gender,
        :email,
        :cell_phone,
        :work_phone,
        :location_id,
        :language_id,
        :homeroom_teacher_id,
        :lunch_period,
        :diploma_level,
        :employablilty_skills,
        :employablilty_skills_pathway,
        :post_secondary_competencies,
        :post_secondary_competencies_pathway,
        user_attributes: [:id, :active, :username]
      )
    end

    def student_props(student)
      {}.tap do |props|
        props[:id] = student.id
        props[:family_id] = student.family_id
        props[:first_name] = student.first_name
        props[:last_name] = student.last_name
        props[:middle_name] = student.middle_name
        props[:nickname] = student.nick_name
        props[:suffix] = student.suffix
        props[:code] = student.code
        props[:birth_date] = student.decorate.birth_date
        props[:date_of_birth] = student.date_of_birth
        props[:age] = student.decorate.age
        props[:gender_label] = student.decorate.gender_label
        props[:gender] = student.gender
        props[:grade] = student.grade
        props[:grade_label] = grade_label(student)
        props[:graduated] = student.graduated?
        props[:graduation_date] = student.decorate.graduation_date
        props[:graduation_day] = student.graduation_day
        props[:graduation_month] = student.graduation_month
        props[:graduation_year] = student.graduation_year
        props[:avatar] = student.path_to_photo
        props[:full_name] = student.full_name(:reverse)
        props[:email] = student.email
        props[:cell_phone] = student.cell_phone
        props[:work_phone] = student.work_phone
        props[:ethnicity] = student.unspecified? ? nil : student.ethnicity
        props[:ethnic_label] = student.decorate.ethnic_label
        props[:homeroom_teacher_id] =
          student.homeroom_teacher_id? ? student.homeroom_teacher_id : nil
        props[:location_id] = student.location_id? ? student.location_id : nil
        props[:lunch_period] = student.lunch_period
        props[:diploma] = student.requirement_label&.name
        props[:diploma_id] = student.requirement_label&.id
        props[:current] = student.current?
        props[:school_year_records] = student.school_year_students
        props[:category_ids] = student.category_ids
        props[:families] = student.families.map { |f| family_props(f) }
        props[:photo_url] = student.path_to_photo
        props[:user_attributes] = {
          id: student.decorate.user_id,
          username: student.decorate.user_username,
          active: student.decorate.user_active
        }
        props[:races] = student.races.map(&:name)
        props[:race_labels] = student.races.map(&:name).join(', ')
        props[:homeroom_teacher_name] = student.decorate.homeroom_teacher_full_name
        props[:location_name] = student.decorate.location_name
        props[:diploma_level] = student.diploma_level
        props[:employablilty_skills] = student.employablilty_skills
        props[:employablilty_skills_pathway] = student.employablilty_skills_pathway
        props[:post_secondary_competencies] = student.post_secondary_competencies
        props[:post_secondary_competencies_pathway] = student.post_secondary_competencies_pathway
        props[:primary_email] = student.primary_email_address
        props[:primary_suppression] = student.primary_email_address&.suppression
        props[:summer_graduate] = student.graduation_year == school_year.academic_year - 1 &&
          [7, 8, 9].include?(student.graduation_month)
        language_id = student.language_id.zero? ? nil : student.language_id
        props[:language_id] = language_id
        props[:language_label] = language_label(language_id)
      end
    end

    def family_props(family)
      {}.tap do |props|
        props[:id] = family.id
        props[:name] = family.name
        props[:primary_contacts] = family.contacts.primary.map { |c| contact_props(c) }
      end
    end

    def contact_props(contact)
      {}.tap do |props|
        props[:id] = contact.id
        props[:first_name] = contact.first_name
        props[:last_name] = contact.last_name
      end
    end

    def grade_label(student)
      grade_levels[student.grade]
    end

    def students
      current_school.students
    end

    def student
      @student ||= students.find_by(id: params[:id])
    end
end
