class Ecs::CreateTrainingObjectiveService < ApplicationService
  include AcceptsNestedAttributesHelper

  attr_reader :training_objective, :params

  def initialize(ec_year, params)
    @params = params
    @training_objective = ec_year.ec_training_objective || ec_year.build_ec_training_objective
  end

  def call
    training_objective.content = params[:content].to_s.strip

    attributes = build_accepts_nested_attributes(
      training_objective,
      training_objective.ec_training_subitems,
      params[:training_subitems],
      &method(:training_subitem_param_handler)
    )
    training_objective.assign_attributes(ec_training_subitems_attributes: attributes)

    training_objective.save!
    training_objective
  end

  private

  def training_subitem_param_handler(item)
    item[:content] = item[:content].to_s.strip
  end
end