require 'spec_helper'

describe Supplier do
  let(:supplier){ build :supplier }

  describe '.reset_counters!' do
    it 'sets the counters to the right values' do
      supplier1 = create :supplier
      supplier2 = create :supplier
      create_list :order, 2, :placed, supplier: supplier1
      create_list :order, 7, :active, supplier: supplier1
      create_list :order, 3, :placed, supplier: supplier2
      Supplier.reset_counters!
      supplier1.orders_placed_count.should == 2
      supplier1.orders_in_process_count.should == 7
      supplier2.orders_placed_count.should == 3
    end

    it 'cleans counter values if orders are no longer available' do
      old_connection = Qwaiter::Counter.connection
      # this spec should run on the couchbase database
      Qwaiter::Counter.connection = $cb
      supplier = create :supplier
      Qwaiter::Counter.set "supplier_counter:#{supplier.id}:orders_placed", 9
      supplier.orders_placed_count.should == 9
      Supplier.reset_counters!
      sleep 0.5
      supplier.orders_placed_count.should == 0
      Qwaiter::Counter.connection = old_connection
    end
  end

  describe '#reset_counters!' do
    it 'sets the counters to the right values' do
      supplier = create :supplier
      create_list :order, 5, :placed, supplier: supplier
      create_list :order, 9, :active, supplier: supplier
      supplier.reset_counters!
      supplier.orders_placed_count.should == 5
      supplier.orders_in_process_count.should == 9
    end
  end

  # property open
  describe :open do
    it 'should be false by default' do
      supplier.open.should == false
    end

    it 'should not be open? by default' do
      supplier.open?.should == false
    end

    it 'should be closed? by default' do
      supplier.closed?.should == true
    end

    describe :mark_as_open! do
      before :each do
        supplier.mark_as_open!
      end
      it 'should be persisted in the database' do
        supplier.reload
        supplier.open.should == true
      end

      it 'should be open?' do
        supplier.open?.should == true
      end

      it 'should not be closed?' do
        supplier.closed?.should == false
      end

    end

    describe :mark_as_closed! do
      before :each do
        supplier.mark_as_open!
        supplier.mark_as_closed!
      end

      it 'should be persisted in the database' do
        supplier.reload
        supplier.open.should == false
      end

      it 'should be open?' do
        supplier.open?.should == false
      end

      it 'should not be closed?' do
        supplier.closed?.should == true
      end
    end

  end

  describe '#decrement_orders_placed_count!' do
    it 'decreases orders_placed' do
      Qwaiter::Counter.set "supplier_counter:#{supplier.id}:orders_placed", 9
      supplier.decrement_orders_placed_count!.should == 8
    end
  end

end
