require 'xcodeproj/project'
require 'xcodeproj/project/object/build_phase'

Xcodeproj::Project::Object::PBXCopyFilesBuildPhase.instance_eval do
  def self.new_pod_dir(project, pod_name, path)
    new(project, nil, {
      "dstPath" => "Pods/#{path}",
      "name"    => "Copy #{pod_name} Public Headers",
    })
  end
end

module Pod
  class Project < Xcodeproj::Project

    # Shortcut access to the `Pods' PBXGroup.
    def pods
      groups.find { |g| g.name == 'Pods' } || groups.new({ 'name' => 'Pods' })
    end

    # Adds a group as child to the `Pods' group.
    def add_pod_group(name)
      pods.groups.new('name' => name)
    end
    
    # TODO do we need this?
    def build_configuration(name)
      build_configurations.find { |c| c.name == name }
    end

    def self.for_platform(platform)
      Pod::Project.new.tap do |project|
        project.main_group << project.groups.new('name' => 'Pods')
        project.build_settings('Debug').merge!(build_settings(platform))
        project.build_settings('Release').merge!(build_settings(platform))
      end
    end

    private

    # TODO this needs to be added to each individual target
    def self.build_settings(platform)
      settings = {}
      if platform.requires_legacy_ios_archs?
        settings['ARCHS'] = "armv6 armv7"
      end
      if platform == :ios && platform.deployment_target
        settings['IPHONEOS_DEPLOYMENT_TARGET'] = platform.deployment_target.to_s
      end
      settings
    end
  end
end
