class Admins::CompetitionNavSettingService < ApplicationService
  attr_reader :competition, :params

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

  def call
    ActiveRecord::Base.transaction do

      # hidden_module_type = competition.all_module_types - params[:module_type]
      # competition.competition_modules.where(module_type: hidden_module_type).update_all(hidden: 1)

      old_module_ids = competition.competition_modules.pluck(:id)
      module_ids = []
      params[:navbar].each do |nav|
        if nav["module_id"]
          module_ids << nav["module_id"].to_i
          com_module = competition.competition_modules.find_by(id: nav["module_id"])
        else
          com_module = CompetitionModule.create!(competition_id: competition.id, module_type: 'md')
        end
        com_module.update_attributes!(hidden: nav["hidden"] && nav["hidden"].to_i == 0 ? 0 : 1, position: nav["position"] ? nav["position"] : params[:navbar].length, name: nav["name"], url: nav["url"])
      end

      delete_module_ids = old_module_ids - module_ids
      competition.competition_modules.where(id: delete_module_ids).destroy_all

      competition.update_attributes!(enroll_end_time: params[:enroll_end_time])
      if params[:competition_staffs].present?
        competition.competition_staffs.delete_all
        params[:competition_staffs].each_with_index do |staff_params, index|
          competition.competition_staffs.create!(staff_params.merge(position: index + 1))
        end
      end

      competition
    end
  end
end