module Games
  class AddBoxart < Games::Base
    BUCKET = Settings.boxart.bucket
    REGION = Settings.boxart.region
    S3_URL_PREFIX = "https://#{BUCKET}.s3-#{REGION}.amazonaws.com/"
    self.service_endpoint = Settings.boxart.endpoint
    DISCOVERY_URL = Settings.discovery.endpoint + "/game"

    attributes :name, :image, :discovery_art
    self.primary_attribute = :name
    validates :name, :image, presence: true

    def self.find(name)
      response = get DISCOVERY_URL, params: {name: name}

      if response.success?
        return from_attributes(
          :name => response.body["name"],
          :discovery_art => response.body["boxArt"]
        )
      end

      return from_errors(response.body["message"])
    end

    def save
      return false unless valid?

      response = put "/boxart/#{CGI.escape(name)}", body: save_params

      self.errors = response.body["message"] unless response.success?

      response.success?
    end

    def url
      return "#{S3_URL_PREFIX}#{CGI.escape(self.name)}.jpg"
    end

    private

    def save_params
      {
        :file => Base64.encode64(File.open(image.tempfile.path, &:read))
      }.to_json
    end

  end
end
