module PageObjectExtensions
  module IndexedProperties
    class CollectionOfElements
      include PageObject
      extend Accessors

      def initialize(browser, index, identifier_list)
        initialize_browser(browser)
        identifier_list.each do |identifier|
          type = identifier[0]
          name = identifier[1]
          element_identifiers = identifier[2].clone # Cannot modify the original...
          how_and_what = transform_element_identifiers(element_identifiers, index)
          self.class.send type, name, how_and_what unless Class.instance_methods.include? name
        end
      end

      private

      def transform_element_identifiers(identifiers, index)
        identifiers.each do |key, value|
          identifiers[key] = if key == :index
                               (value % index).to_i
                             elsif value.is_a? Regexp # can't use %s with regex
                               value
                             else
                               value % index
                             end
        end
      end
    end
  end
end
