class Ecs::CreateCourseAchievementMethodsForm
  include ActiveModel::Model

  attr_accessor :ec_course, :course_achievement_methods

  validates :course_achievement_methods, presence: true

  validate :check_total_percentage
  def check_total_percentage
    total_percentage = course_achievement_methods.sum { |item| item[:percentage].to_i }
    if total_percentage > 100 || total_percentage < 0
      errors.add(:course_achievement_methods, :percentage_error)
    end
  end

  def validate!
    super
    return unless errors.blank?
    course_achievement_methods.each { |item| SubForm.new(item.merge(ec_course: ec_course)).validate! }
  end

  class SubForm
    include ActiveModel::Model

    attr_accessor :ec_course
    attr_accessor :id, :course_evaluation_id, :course_evaluation_subitem_ids, :score, :percentage

    validates :course_evaluation_id, presence: true
    validates :course_evaluation_subitem_ids, presence: true
    validates :score, presence: true, numericality: { only_integer: true }
    validates :percentage, presence: true, numericality: { greater_than_or_equal_to: 0, less_than_or_equal_to: 100 }

    validate :check_course_evaluation_id_valid
    def check_course_evaluation_id_valid
      return if ec_course.ec_course_evaluations.exists?(id: course_evaluation_id)

      errors.add(:course_evaluation_id, :record_not_exist)
    end

    validate :check_course_evaluation_subitem_ids_valid
    def check_course_evaluation_subitem_ids_valid
      relations = ec_course.ec_course_evaluation_subitems.where(id: course_evaluation_subitem_ids)
      return if relations.count == course_evaluation_subitem_ids.size

      errors.add(:course_evaluation_subitem_ids, :record_not_exist)
    end
  end
end
