class ArtifactsController < ApiController

  respond_to :json

  # retrieve all available client downloads
  def client_downloads
    clients = ArtifactUpdate.where("product like '%JamClient%' and environment = '#{ArtifactUpdate::DEFAULT_ENVIRONMENT}'").order(:product)

    result = {}

    clients.each do |client|
      url = determine_url(client)
      result[client.product] = { :uri => url, :size => client.size }
    end
    render :json => result, :status => :ok
  end


  def versioncheck

    # the reported client version
    #client_version = params[:ver]

    # the name of the client, i.e.JamClient
    product = params[:product]

    # the os (Win32/MacOSX/Unix)
    os = params[:os]

    product = "#{product}/#{os}"

    logger.debug "version check from #{product}"



    unless ArtifactUpdate::PRODUCTS.include? product
      render :json => { :errors => { :product => ['not a valid product'] } }, :status => :unprocessable_entity
      return
    end

    @artifact = ArtifactUpdate.find_by_product_and_environment(product, ArtifactUpdate::DEFAULT_ENVIRONMENT)

    if @artifact.nil?
      render :json => {}, :status => :ok
    else
      url = determine_url(@artifact)

      render :json => { "version" => @artifact.version, "uri" => url, "sha1" => @artifact.sha1, "size" => @artifact.size }, :status => :ok
    end
    
  end

  def determine_url(artifact)
    if SampleApp::Application.config.storage_type == :file
      # this is basically a dev-time only path of code; we store real artifacts in s3
      url = SampleApp::Application.config.jam_admin_root_url + artifact.uri.url
    else
      url = artifact.uri.url
    end

    return url
  end

end
