# See the loader file for license and author info

require 'sketchup.rb'
module CLF_Extensions_NS

  module Clf_Loose_To_Groups

    # Make groups of all geometry in the selection set or active_entities.
    def self.main
      model = Sketchup.active_model
      @entities = model.active_entities
      sel = model.selection
      if sel[0]
        ents = sel.to_a
      else
        ents = @entities.to_a
      end
      
      if ents.length == 0
        return
      end
      
      if Sketchup.version_number < 7000000
        model.start_operation "Loose to Groups"
      else
        model.start_operation "Loose to Groups", true
      end
      
      #this divides the given entities into groups of 1000 and then sends them to be turned into groups
      chunk = 1000
      ents_count = ents.length
      count = (ents.length/chunk)+1
      new_arr = []
      @top_level = ents[0].parent
      count.times do |e|
        place_number = (e*chunk)
        new_arr = ents[place_number,chunk]
        maker(new_arr, place_number, ents_count)
      end
      model.commit_operation
    end
    
    #this takes each given entity, finds all_connected, then adds all that to a groups, unless the given entity is already a part of a group
    #That would happen when an entity it was connected to was already sent to this method in a previous block.
    def self.maker(ents, place_number, ents_count)
      total_ents = ents.length
      while ents.length > 0
        Sketchup.set_status_text "Processing #{(total_ents-ents.length)+place_number} of #{ents_count} entities.", SB_PROMPT
        if ((ents[0].is_a? Sketchup::Edge) || (ents[0].is_a? Sketchup::Face)) && ents[0].parent == @top_level
          to_group = ents[0].all_connected
          ents = ents - to_group
          group = @entities.add_group(to_group)
        else
          ents = ents - [ents[0]]
        end
      end
    end # maker
  end

end