module Boxart
  class Game < Boxart::Base
    BUCKET = Settings.boxart.bucket
    REGION = Settings.boxart.region
    S3_URL_PREFIX = "https://#{BUCKET}.s3-#{REGION}.amazonaws.com/"
    DISCOVERY_URL = "http://discovery-production.prod.us-west2.twitch.tv/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}

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

      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}#{URI.encode(self.name)}.jpg"
    end

    private

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