module Games
  class AddGameBanner < Games::Base
    attributes :name, :banner_image_url, :image, :game_id
    self.primary_attribute = :name

    validates :name, :image, presence: true

    def self.find(name)
      response = get "/game", params: {name: name}
      return from_errors(response.body["error"]) unless response.success?

      return from_attributes(
        :game_id => response.body["id"],
        :name => name,
        :banner_image_url => response.body["localized_game_banner_url"]
      )
    end

    def save
      response = put "/banner", body: URI.encode_www_form(save_params), headers: {'Content-Type' => 'application/x-www-form-urlencoded'}

      self.errors.add(:base, response.body["error"]) unless response.success?

      response.success?
    end

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

  end
end
