require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
require 'time_travel'

describe IspUsage::Fetchers::Fetcher do
  describe "usage hash" do
    it "without month end" do
      @usage = IspUsage::Fetchers::Fetcher.new(:username => 'bob', :password => 'xkcd')
      @usage.new_usage_period(:used => 500, :quota => 1000, :label => 'All Day')
      @usage.to_hash.should == {
        :usage_periods => [{:used => 500, :quota => 1000, :total => 1000, :label => 'All Day', :type => :meter}],
        :isp => 'Fetcher',
        :username => 'bob'
      }
    end

    it "with month end" do
      at_time '2010-02-04 12:00' do
        @usage = IspUsage::Fetchers::Fetcher.new(:username => 'bob', :password => 'xkcd', :month_end => Time.parse('2010-02-20'))
        @usage.new_usage_period(:used => 500, :quota => 1000, :label => 'All Day')
        @usage.to_hash.should == {
          :usage_periods => [{:used => 500, :quota => 1000, :total => 1000, :label => 'All Day', :type => :meter, :month_megabytes_used => 500}],
          :isp => 'Fetcher',
          :username => 'bob',
          :month_end => Time.parse('2010-02-20'),
          :month_used => 50
        }
      end
    end
  end
  
  it "should return an error" do
    @usage = IspUsage::Fetchers::Fetcher.new(:username => 'bob', :password => 'xkcd')
    @usage.error = "Invalid username/password"

    @usage.to_hash.should == {
            :isp => 'Fetcher',
            :username => 'bob',
            :error => "Invalid username/password",
            :usage_periods => []
    }
  end

  describe "month used" do
    before do
      @usage = IspUsage::Fetchers::Fetcher.new({})
      @usage.month_end = Time.parse('2010-02-22')
    end
    
    it "should be 100% at the end of the month" do
      at_time '2010-02-22' do
        @usage.month_used.should == 100
      end
    end

    it "should be 0% at the start of the month" do
      at_time '2010-01-22' do
        @usage.month_used.should == 0
      end
    end

    it "should be 50% in the middle of the month" do
      at_time '2010-02-6 12:00' do
        @usage.month_used.should == 50
      end
    end
  end

  describe "month megabytes used" do
    before do
      @usage = IspUsage::Fetchers::Fetcher.new({})
      @usage_period = IspUsage::UsagePeriod.new(@usage)
      @usage_period.quota = 50000
      @usage.usage_periods << @usage_period
      @usage.month_end = Time.parse('2010-02-22')
    end

    it "should be 50000MB at the end of the month" do
      at_time '2010-02-22' do
        @usage_period.month_megabytes_used.should == 50000
      end
    end

    it "should be 0MB at the start of the month" do
      at_time '2010-01-22' do
        @usage_period.month_megabytes_used.should == 0
      end
    end

    it "should be 25000MB in the middle of the month" do
      at_time '2010-02-6 12:00' do
        @usage_period.month_megabytes_used.should == 25000
      end
    end
  end
end