class MoveCommonPropertiesToRootPom
  @@reactorHandler = ReactorHandler.new
  @@modulePomPaths = nil
  def findCommonProperties (project_directory_path)
    @@modulePomPaths =  @@reactorHandler.fetchGidArtifactIdAndVersionFromChildModule(project_directory_path,false)
    allModuleProperties = Array.new
    commonProperties = Array.new
    @@modulePomPaths.each do |modulePomPath|
      modulePomDoc = Nokogiri::XML(open(modulePomPath))
      modulePomDoc.css("project/properties").children.each do |property|
        if property.name != 'text' && property.name != 'comment'
          propertyNameValue = "#{property.name}:#{property.text}"
          allModuleProperties.push(propertyNameValue)
        end
      end
    end
    allModuleProperties.uniq.each do |property|
      if allModuleProperties.count(property) == @@modulePomPaths.length
        commonProperties.push(property)
      end
    end
    return commonProperties
  end
  
  def writeCommonPropertiesToReactorPom (project_directory_path,commonProperties)
    reactorPomPath = "#{project_directory_path}/pom.xml"
    pom_document = @@reactorHandler.parse_xml_from_file(reactorPomPath)
    nokObj = Nokogiri::XML::Node
    projectNode =  pom_document.at('project')
    propertiesNode =  nokObj.new('properties',projectNode)
    commonProperties.each do |property|
      propNameValue = property.split(':')
      propName = propNameValue[0]
      propValue = propNameValue[1]
      propNode = nokObj.new(propName,projectNode)
      propNode.content = propValue
      propertiesNode.add_child(propNode)
    end
    dependencyHandler = DependencyHandler.new
    pomObj = dependencyHandler.add_node_element('project',propertiesNode,pom_document)
    File.write(reactorPomPath,pomObj)
    puts "Moved common properties to reactor pom!!!"
  end
  
  def removeCommonPropertiesfromModules (project_directory_path,commonProperties)
    
    @@modulePomPaths.each do |eachModulePath|
      pom_document = @@reactorHandler.parse_xml_from_file(eachModulePath)
      commonProperties.each do |property|
        propNameValue = property.split(':')
        propName = propNameValue[0]
        pom_document.css('project/properties').children.each do |eachProperty|
          if eachProperty.name == propName
            eachProperty.remove
          end
        end        
      end
    File.write(eachModulePath,pom_document)
    end
    puts "Common properties removed from child modules!!!"
  end 
end