require "page-object"

module FileSystemHelpers
  module Downloader
    class << self
      # Initializes the class and downloads the file(s) specified in url_list
      #
      # url_list - String or Array of URL(s) we wish to download.
      #
      # Examples
      #
      #   download('site.com/file.txt', 'anothersite.com/file2.txt')
      #   # will download both files to the default download directory
      #
      #   download('path.com/new_file.xls')
      #   # will download the single file to the default download directory
      #
      # Returns the Array of downloaded files
      def download(*url_list, with_timestamp: true)
        downloaded = []
        url_list.each do |url|
          downloaded << download_with_open_uri(url, with_timestamp: with_timestamp)
        end
        downloaded
      end

      private

      def grab_session_cookie
        # Workaround because @browser.cookies.to_a fails on remote chromedriver:
        cookie_array = BROWSER.cookies
        found = cookie_array.find { |cookie| cookie.include? "PHPSESSID" }
        fail "Could not find PHPSESSID cookie. All cookies found: #{cookie_array}" unless found
        found.strip
      end

      # Use the cookie session to download the file via open-uri (similar to curl),
      # directly to the project Support::Paths.downloads
      def download_with_open_uri(url, with_timestamp:)
        file_name = URI(url).path.split("/").last
        name_without_ext = File.basename(file_name, ".*")
        ext = File.extname(file_name)
        appended_timestamp = with_timestamp ? "_#{Time.stamp}" : nil
        save_location = File.join(Support::Paths.downloads, "#{name_without_ext}#{appended_timestamp}#{ext}")

        # cookie_string = grab_session_cookie

        File.open(save_location, "wb") do |saved_file|
          # the following "open" is provided by open-uri
          # INVESTIGATE THIS FURTHER!!!!
          # open(url, "rb", "Cookie" => cookie_string) do |read_file|
          open(url, "rb") do |read_file|
            saved_file.write(read_file.read)
          end
        end
        save_location
      end
    end
  end
end
