require 'spec_helper'

vcr_options = {}
describe Traxii::OnApp::CDN::Resource do
  before(:all) do
    @user = load_user
    Traxii.setup.set_auth(@user.login, @user.login.upcase)
  end

  let :resource_data do
    {
        cdn_hostname: 'testapi2.com',
        resource_type: 'HTTP_PULL',
        edge_group_ids: [29],
        origin: 'cdn.test.api.com'
    }
  end

  context 'managing a resource', :focus do
    it 'use customer user to auth' do
      expect(Traxii.setup.username).to eq(@user.login)
    end

    it 'create with basic resource' do
      resource = described_class.create(resource_data)
      expect(resource).not_to be_nil
      expect(resource.id).not_to be_nil

      @@resource = resource
    end

    it 'find created resource' do
      resource = described_class.find(@@resource.id)
      expect(resource.id).to eq(@@resource.id)
      expect(resource.login).to eq(@@resource.login)
    end

    it 'suspend resource', :focus do
      @@resource.suspend
      expect(@@resource.status).to eq('suspended')
    end

    it 'resume resource', :focus do
      @@resource.resume
      expect(@@resource.status).to eq('resumed')
    end

    it 'destroy resource', :focus do
      @@resource.destroy
      expect(described_class.find(@@resource.id)).to be_nil
    end
  end

  describe '#all' do
    it 'returns a resource list' do
      expect(described_class.all).to be_a(Array)
    end

    it "has #{described_class.class} member" do
      expect(described_class.all.first).to be_a(described_class)
    end

    it 'returns only vod resources' do
      expect(described_class.all('vod')).to be_a(Array)
    end

    it 'returns only http resources' do
      expect(described_class.all('http')).to be_a(Array)
    end

    it 'returns only live_streaming resources' do
      expect(described_class.all('live_streaming')).to be_a(Array)
    end

    it 'raise a error if type not exists' do
      expect { described_class.all('test') }.to raise_error(Traxii::OnApp::CDN::Resource::TypeError, "type 'test' not exist.")
    end
  end

  describe '#find', :vcr do
    it 'returns a resource' do
      expect(described_class.find(1)).to be_a(described_class)
    end

    it 'return nil if not found' do
      expect(described_class.find(999999)).to be_nil
    end

    it 'contains the resource data' do
      obj = described_class.all.first
      expect(obj.user_id).not_to be_nil
      expect(obj.cdn_hostname).not_to be_nil
      expect(obj.resource_type).not_to be_nil
      expect(obj.last_24h_cost).not_to be_nil
      expect(obj.origins).not_to be_nil
      expect(obj.cname).not_to be_nil
      expect(obj.created_at).not_to be_nil
      expect(obj.updated_at).not_to be_nil
    end
  end

  describe '.advanced', :vcr => { :record => :new_episodes } do
    let(:resource) { described_class.find(1) }

    it 'return a AdvancedResource instance' do
      expect(resource.advanced).to be_a(Traxii::OnApp::CDN::ResourceAdvanced)
    end
  end
end
