class ArtifactsController < ApiController

  respond_to :json

  # retrieve all available client downloads
  def client_downloads

    # jamblaster specifies this params[:type]
    is_jamblaster = params[:type] && params[:serialno]

    if is_jamblaster
      # check and see if there is a build just for this JB
      clients = ArtifactUpdate.where('product ilike ? and environment = ?', "JamClient/#{params[:type]}", params[:serialno]).order(:product)
      if clients.count == 0
        # if not, then fine, give back the default environment
        clients = ArtifactUpdate.where('product ilike ? and environment = ?', "JamClient/#{params[:type]}", ArtifactUpdate::DEFAULT_ENVIRONMENT).order(:product)
      end
    else
      clients = ArtifactUpdate.where("product like '%JamClient%' and environment = '#{ArtifactUpdate::DEFAULT_ENVIRONMENT}'").order(:product)
    end

    if is_jamblaster && params[:serialno]
        Jamblaster.bootstrap(params[:serialno])
    end

    #Parameters: {"serialno"=>"NCA-001-160602-00084", "version"=>"dev-20161120-153542", "type"=>"jamblaster"}
    #Parameters: {"serialno"=>"NCA-001-160602-00084", "version"=>"dev-20161120-153542", "type"=>"jamblasterclient"}

    result = {}

    clients.each do |client|
      url = client.determine_url

      # jamblaster specifies this params[:type]
      if is_jamblaster
        result[params[:type]] = { :uri => url, :size => client.size, :version => client.version, :md5 => client.sha1}
      else
        result[client.product] = { :uri => url, :size => client.size, :version => client.version, :md5 => client.sha1}
      end
    end
    render :json => result, :status => :ok
  end


  def healthcheck
    render :json => {}
  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 = @artifact.determine_url

      # client can't deal with https
      if url.start_with?('https://')
        url = url.gsub('https://' ,'http://')
      end
      render :json => { "version" => @artifact.version, "uri" => url, "sha1" => @artifact.sha1, "size" => @artifact.size }, :status => :ok
    end
    
  end

end
