require 'date'
require 'logger'

require_relative '../../../common/job_helper'
require_relative '../../../common/models/models'
require_relative '../helpers/configuration_helper'
require_relative '../helpers/worker_helper'
require_relative '../worker'
require_relative 'resource_fetcher'

module ExternalMemory
  module Workers
    module Resource

      # Worker that process jobs about resources
      class ResourceWorker < Worker

        include ExternalMemory::JobHelper
        include ExternalMemory::Workers::Helpers::ConfigurationHelper
        include ExternalMemory::Workers::Helpers::WorkerHelper

        MAX_DOWNLOAD_SIZE_KEY = 'max_download_size'

        def services
          [FETCH_RESOURCE_SERVICE]
        end

        def initialize(configuration)
          @logger = Logger.new(STDOUT)
          @max_download_size = Integer(read_item(configuration, MAX_DOWNLOAD_SIZE_KEY))
        end

        def process(service_name, execution_parameters, execution_context)
          element_url_id = execution_parameters['element_url_id']
          element_url = element_url_without_resource(element_url_id)

          url = execution_parameters['url'] || element_url.url
          resource = ExternalMemory::Resource.by_url(url)
          if resource
            element_url.resource_id = resource.id
            element_url.save
            "The resource [#{resource.id}] match the element url [#{element_url.id}] for url [#{url}]"
          else
            redirections_left = execution_parameters['redirections_left'] || 10
            ResourceFetcher.new(element_url, url, redirections_left, @max_download_size, execution_context).process
          end
        end

      end
    end
  end
end
