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

    if params.key?(:training_subitems)
      attributes = build_accepts_nested_attributes(
        training_objective,
        training_objective.ec_training_subitems,
        params[:training_subitems],
        &method(:training_subitem_param_handler)
      )
      attributes.each_with_index { |attr, index| attr[:position] = index + 1 }
      training_objective.assign_attributes(ec_training_subitems_attributes: attributes)
    end

    training_objective.save!
    training_objective
  end

  private

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