class Admin::Accounting::Students::MatricesController < Admin::Accounting::Controller
  def show
    render_success :ok, json: matrices.build_all(student).map { |m| matrix_props(m) }
  end

  def update
    objects = []
    subcategories.each do |subcategory|
      data = params[subcategory.id.to_s]
      matrix = matrices.find_or_initialize_by(subcategory: subcategory)
      matrix.viewable = data[:viewable]
      matrix.primary = data[:primary].to_i.floor
      secondary = data[:secondary].to_i.floor
      validate_matrix(matrix, subcategory, matrix.primary + secondary)
      objects << matrix
    end

    if transactional_save(objects)
      render_success :ok
    else
      errors = objects.map { |o| o.errors.full_messages }.flatten
      render_error :unprocessable_entity, errors: errors
    end
  end

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

    def matrices
      student.accounting_student_matrices
    end

    def subcategories
      current_school.accounting_subcategories
    end

    def matrix_props(matrix)
      {
        id: matrix.id,
        student_id: matrix.student_id,
        subcategory_id: matrix.subcategory_id,
        name: matrix.subcategory.decorate.title,
        primary: matrix.decorate.primary_percentage,
        secondary: matrix.decorate.secondary_percentage,
        viewable: matrix.viewable
      }
    end

    def validate_matrix(matrix, subcategory, total)
      return if total == 100

      error = "#{subcategory.decorate.title} percent needs to equal 100"
      matrix.add_custom_error(:base, error)
    end
end
