#!/usr/bin/env ruby

require "google_drive"
require "highline/import"
require "active_support/all"


def determine_name_from_email!
  return unless @@config[:email]
  @@config[:name] = @@config[:email].split("@")[0].humanize
end

def session
  @@session ||= GoogleDrive.login(@@config[:email], @@config[:password])
end

def schedule
  @@schedule ||= session.spreadsheet_by_key(@@config[:spreadsheet]).worksheets[0]
end


def store_config!
  File.open(@@config[:config_file], 'wb+') { |f| f.write([@@config[:email], @@config[:password], @@config[:name]].join(',')) }
end

def load_config!
  if File.exists?(@@config[:config_file])
    say "Loading config from #{@@config[:config_file]}"
    @@config[:email], @@config[:password], @@config[:name] = File.read(@@config[:config_file]).split(',')
  end
end

def get_entries!
  puts "\n\n"
  schedule.rows.each_with_index do |row, index|
    next if index < @@config[:skip_rows]
    if is_us?(row) and has_hours?(row)
      header = project_header_for_row(row, index)
      print_formatted_row(row, header)
    end
  end
end

def is_us?(row)
  return row.to_s.include?(@@config[:name])
end

def has_hours?(row)
  return row[5].present?
end

def print_formatted_row(row, header)
  formatted_row = row[4].tap do |desc|
    desc << " (#{row[5]} hours)"
    desc.insert(0, "<%= color('#{header}\n', :cyan) %>")
  end
  say formatted_row
  puts "\n"
end

# Step up through the worksheet until we find a row that meets our requirements
def project_header_for_row(row, index)
  return nil if row.nil?

  # Does the row meet our requirements:
  # - one column present only
  # - only first column filled in
  return row[0] if !row[0].blank? && row[1].blank? 

  # Otherwise recurse
  return project_header_for_row(schedule.rows[index - 1], index - 1)
end



@@config = {
  spreadsheet: "0AlNg4D7kwNRpcG5vSU0wNmY2TkRoU29UcEktZUkxV3c",
  skip_rows: 10,
  config_file: File.expand_path("~/.staff_schedule")
}

say("<%= color('What am I doing this week?!', :green) %>")
load_config!

if @@config[:email].nil?
  @@config[:email] = ask("Imma gonna need your email username:\t")
  determine_name_from_email!

  unless agree("Is your name in the schedule #{@@config[:name]}?\t")
    @@config[:name] = ask("Imma gonna need your name in the staff schedule as well then:\t")
  end
end

if @@config[:password].nil?
  @@config[:password]  = ask("Imma gonna need you to generate a one time password (2-factor auth), or enter your account password:\t") { |q| q.echo = "*" }
end



store_config!
get_entries!







