#!/usr/bin/ruby

require 'basecamp' # uses the Ruby wrapper provided by 37signals (http://developer.37signals.com/basecamp/basecamp.rb)

Basecamp.establish_connection!('<your basecamp url>', '<your bc user>', '<your bc pass>', true)

OVERLIMIT_RATE = 100

session = Basecamp.new

projects = Basecamp::Project.find(:all)

projects.each { |proj|
  categories = Basecamp::Category.post_categories(proj.id)

  category = categories.find { |cat| cat.name == 'Automator Config' }

  if category != nil
    config_msgs = Basecamp::Message.recent(proj.id, {:category_id => category.id })
    msg = config_msgs.first
    if msg != nil
      config = YAML::load(msg.body)

      run_dates = config['Run Dates'].split(",").collect{|x| x.to_i } if config.key?('Run Dates')

      if run_dates && run_dates.include?(Time.now.day)
        summary_category = categories.find { |cat| cat.name == 'Usage Summaries' }

        if summary_category == nil
          summary_category = Basecamp::Category.new(:project_id => proj.id)
          summary_category.type = 'post'
          summary_category.name = 'Usage Summaries'
          summary_category.save
        end

        limit = 0
        limit = config['Limit'] if config.key?('Limit')

        to = Time.new
        from = Time.local(to.year, to.mon, 1)

        from_str = from.strftime('%Y%m%d')
        to_str = to.strftime('%Y%m%d')

        time_entries = Basecamp::TimeEntry.report({:filter_project_id => proj.id, :from => from_str, :to => to_str})
        hours_people = Hash.new

        time_entries.each do |te|
          if hours_people.key?(te.person_id)
            hours_people[te.person_id] += te.hours 
          else
            hours_people[te.person_id] = te.hours 
          end
        end

        message = Basecamp::Message.new(:project_id => proj.id)
        message.category_id = summary_category.id
        message.title = 'Usage Summary'
        body = ''
        if config.key?('Limit')
          limit = config['Limit']
          body = 'Your usage since the 1st of the month is: <br />'
          total = 0
          hours_people.each { |key,value|
            person = session.person(key)
            name = person.first_name + " " + person.last_name
            sub_total = value * config[name] if config.key?(name)
            total += sub_total
            body += name + " : $" + sub_total.to_s + " (" + value.to_s + ") " +"<br />"
          }
          body += "Total: $" + total.to_s
          body += "<br />You are under your limit by $" + (limit - total).to_s if limit >= total
          body += "<br />You are over your limit by $" + (total - limit).to_s if total > limit
        else
          sum = 0
          hours = 0
          hours = config['Hours'] if config.key?('Hours')
          hours_people.each_value { |hours| sum += hours }
          body = 'You have used ' + sum.to_s + ' hours for the month.<br />'
          body += 'You have ' + (hours - sum).to_s + ' hours remaining' if hours >= sum
          body += 'You are over by ' + (sum - hours).to_s + ' hours, resulting in additional charges of $' + ((sum - hours) * OVERLIMIT_RATE).to_s  if sum > hours
        end
        message.body = body
        message.save
      end
    end
  end
}

