module Pod
  module Generator

    class Acknowledgements
      require "xcodeproj/xcodeproj_ext"

      def initialize(target_definition, pods)
        @target_definition, @pods = target_definition, pods
      end

      def save_in_directory(pathname)
        Xcodeproj.write_plist(plist, pathname + filename)
      end

      def filename
        result = "#{@target_definition.label}-Acknowledgements.plist"
        if result.start_with?"Pods-"
          result
        else
         "Pods-" + result
        end
      end

      def plist
        {
          :Title => "Acknowledgements",
          :StringsTable => "Acknowledgements",
          :PreferenceSpecifiers => licenses
        }
      end

      def licenses
        licences_array = [header]
        @pods.each do |pod|
          if (hash = hash_for_pod(pod))
            licences_array << hash
          end
        end
        licences_array << footnote
      end

      def hash_for_pod(pod)
        if (license = pod.license)
          license_hash = {
            :Type => "PSGroupSpecifier",
            :Title => pod.name,
            :FooterText => license[:text]
          }
        else
          puts "[!] No licence for #{pod.name}"
        end
      end

      def header
        {
          :Type => "PSGroupSpecifier",
          :Title => header_title,
          :FooterText => header_text
        }
      end

      def footnote
        {
          :Type => "PSGroupSpecifier",
          :Title => footnote_title,
          :FooterText => footnote_text
        }
      end

      def header_title
        "Acknowledgements"
      end

      def header_text
        "This application makes use of the following third party libraries:"
      end

      def footnote_title
        ""
      end

      def footnote_text
        "Generated by CocoaPods - http://cocoapods.org"
      end
    end
  end
end
