require 'spec_helper'

describe "Artifact API ", :type => :api do
  
  subject { page }

  before(:each) do
    ArtifactUpdate.delete_all
  end

  describe "versioncheck" do
    before do
      @artifact = FactoryGirl.create(:artifact_update)
    end

    it "matches an artifact" do
      get '/api/versioncheck.json', {:os => 'Win32', :product => 'JamClient'}
      last_response.status.should eql(200)
      JSON.parse(last_response.body).should eql({"version" => @artifact.version, "uri" => Rails.application.config.jam_admin_root_url + @artifact.uri.url, "size" => @artifact.size, "sha1" => @artifact.sha1})
    end

    it "matches no artifact" do
      @artifact.delete
      get '/api/versioncheck.json', {:os => 'Win32', :product => 'JamClient'}
      last_response.status.should eql(200)
      JSON.parse(last_response.body).should eql({})
    end

    it "fails on bad product" do
      @artifact.delete
      get '/api/versioncheck.json', {:os => 'what', :product => 'JamClient'}
      last_response.status.should eql(422)
      JSON.parse(last_response.body).should eql({"errors" => {"product" => ['not a valid product']}})
    end
  end

  describe "client_downloads" do

    describe "desktop" do
      before do
        @win_client = FactoryGirl.create(:artifact_update, :product => 'JamClient/Win32')
        @mac_client= FactoryGirl.create(:artifact_update, :product => 'JamClient/MacOSX')

        get '/api/artifacts/clients.json'
        last_response.status.should eql(200)
        @response = JSON.parse(last_response.body)

      end

      it {
        @response.length.should == 2
        @response[@mac_client.product]["size"].should == @mac_client.size
        @response[@mac_client.product]["uri"].should_not be_nil
        @response["JamClient/Win32"]["size"].should == @win_client.size
        @response["JamClient/Win32"]["uri"].should_not be_nil
      }
    end

    describe "jamblaster" do
      before do
        @jb_client = FactoryGirl.create(:artifact_update, :product => 'JamClient/JamBlaster')

        get '/api/artifacts/JamBlaster.json', {serialno: 'abcde'}
        last_response.status.should eql(200)
        @response = JSON.parse(last_response.body)

      end

      it {
        @response.length.should == 1
        @response['JamBlaster']["size"].should == @jb_client.size
        @response['JamBlaster']["uri"].should_not be_nil
        Jamblaster.find_by_serial_no('abcde').should_not be_nil
      }
    end

  end
end
