module Pod
  class SpecBuilder
    def initialize(spec, source, embedded, dynamic, dependenciesPool)
      @spec = spec
      @source = source.nil? ? '{ :path => \'.\' }' : source
      @embedded = embedded
      @dynamic = dynamic
      @dependenciesPool = dependenciesPool
    end

    def framework_path
      if @embedded
        @spec.name + '.embeddedframework' + '/' + @spec.name + '.framework'
      else
        @spec.name + '.framework'
      end
    end

    def framework_path_by_platform(platform)
      return platform.name.to_s + '/' + framework_path
    end

    def spec_platform(platform)
      fwk_base = platform.name.to_s + '/' + framework_path
      spec = <<RB
  s.#{platform.name}.deployment_target    = '#{platform.deployment_target}'
  s.#{platform.name}.vendored_framework   = '#{fwk_base}'
RB

      %w(frameworks weak_frameworks libraries requires_arc xcconfig ).each do |attribute|
        attributes_hash = @spec.attributes_hash[platform.name.to_s]
        next if attributes_hash.nil?
        value = attributes_hash[attribute]
        next if value.nil?

        value = "'#{value}'" if value.class == String
        spec += "  s.#{platform.name}.#{attribute} = #{value}\n"
      end
      spec
    end

    def spec_metadata
      spec = spec_header
      spec
    end

    def spec_close
      "end\n"
    end

    private

    def dependency
      value = @spec.attributes_hash["dependencies"]
      return "\n" if value.nil?
      spec = "\n"
      value.each {|key, value|
        version = ""
        if value.count > 0
          version = value[0]
        end


        dependencySpec = nil
        for d in @dependenciesPool
          if d.name == key
            dependencySpec = d
          end
        end

        if not dependencySpec.nil?
           version = ">=#{dependencySpec.podSpecilication.version.to_s}"
        end

        if version != ""
          spec += "\n s.dependency '#{key}', '#{version}'"
        else
          spec += "\n s.dependency '#{key}'"
        end
      }
      return spec+="\n"
    end

    def spec_header
      spec = "Pod::Spec.new do |s|\n"

      %w(name version summary license authors homepage description social_media_url
         docset_url documentation_url screenshots frameworks weak_frameworks libraries requires_arc
         deployment_target xcconfig vendored_libraries vendored_frameworks preserve_paths static_framework).each do |attribute|
        value = @spec.attributes_hash[attribute]
        next if value.nil?
        value = value.dump if value.class == String
        spec += "  s.#{attribute} = #{value}\n"
      end
      spec += dependency

      spec + "  s.source = #{@source}\n\n"
    end
  end
end