require 'rubygems'
require 'mechanize'

class IspUsage
  class Fetchers
    class AUExetel < Fetcher
      def initialize(options)
        super(options)
      end

      def fetch_usage
        agent = Mechanize.new

        page = agent.get('http://www.exetel.com.au/index_alt.php')
        form = page.form('loginform')
        form.login_name = self.username
        form.password = self.password

        page = agent.submit(form, form.buttons.first)

        month_start = Time.parse(page.search('/html/body/div/div[3]/div[2]/div[2]/div/p').text.match(/Usage From: (\S+)/)[0])
        self.month_end = Time.local(month_start.year, month_start.month + 1, month_start.day)
        page.search('.new_usage_content').each do |usage_div|
          matches = usage_div.text.match(/^(\d+\.\d+)\D+(\d+)/)
          next if matches.nil?
          usage_period = self.new_usage_period
          usage_period.used = matches[1].to_f * 1000
          usage_period.quota = matches[2].to_f * 1000
        end

        usage_periods.first.label = 'Peak'
        usage_periods.last.label = 'Off Peak'
      end
    end
  end
end