class ArrayController
  
  def initialize(array)
    objects_collation NSArray.arrayWithArray(array.dup)
  end
  
  def sections
    @collection
  end

  def objectAtIndexPath(indexPath)
    @collection[indexPath.section][indexPath.row]
  end
  
  alias_method :[], :objectAtIndexPath
  
  def sectionIndexTitleForSectionName(section_name)
    @collection[section_name.upcase]
  end
  
  def sectionAtIndex(id)
    @collection[id] || []
  end
  
  
  def sectionIndexTitles
    UILocalizedIndexedCollation.currentCollation.sectionTitles
  end
  
  def objects_collation(input)
    selector = :name
    index = sectionTitlesCount = UILocalizedIndexedCollation.currentCollation.sectionTitles.count
    collation = UILocalizedIndexedCollation.currentCollation
    
    mutable_sections = Array.new(sectionTitlesCount) { [] }
    input.each do |object|
      section_number = UILocalizedIndexedCollation.currentCollation.sectionForObject(object, collationStringSelector:selector)
      mutable_sections[section_number] << object if object.is_a?(Country)
    end
  
    Dispatch::Queue.concurrent.apply(sectionTitlesCount) do |idx|
      objects_for_section = mutable_sections[idx]
      object = UILocalizedIndexedCollation.currentCollation.sortedArrayFromArray(objects_for_section, collationStringSelector:selector)
      mutable_sections.replaceObjectAtIndex(idx, withObject:object)
    end
    
    @collection = mutable_sections
  end
end