class Admins::CompetitionStageUpdateService < ApplicationService
  attr_reader :competition, :params, :stage

  def initialize(competition, params, stage)
    @params = params
    @competition = competition
    @stage = stage
  end

  def call
    ActiveRecord::Base.transaction do
      stage.update_attributes!(name: params[:stage_name], score_rate: (params[:score_rate].to_i / 100.0).round(2))

      stage.competition_stage_sections.destroy_all

      unless params[:stage].blank?
        params[:stage].each do |section|
          stage_section = CompetitionStageSection.create!(competition_id: competition.id, competition_stage_id: stage.id,
                                                          start_time: section["start_time"], end_time: section["end_time"],
                                                          entry: section["entry"], score_source: section["score_source"])
          section["identifiers"].each do |identifier|
            CompetitionEntry.create!(competition_stage_section_id: stage_section.id, competition_stage_id: stage.id,
                                     shixun_identifier: identifier)
          end
        end
      end

      stage
    end
  end
end