#!/usr/bin/env ruby
=begin
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
=end

# it requires gruff package from gems
# You need to have, obviously, ruby and gems and then install gruff through 
# gem:
#    $ gem install gruff
# Also you should have RMagick, something like that:
#   $ sudo aptitude install librmagick-ruby
# In Ubuntu you have 'ruby' and 'rubygems' packages, but if you are going to
# work more with ruby, i recommend you to install gem from the website 
# (it's trivial)
#    http://rubygems.org/
#
require 'rubygems'
require 'gruff'
require 'date'
require 'ftools'


class GoogleAnalyticsCsvParser
  # Constants about i18n stuff, format date and months names
  DATE_FORMAT = '%d/%m/%Y'  
  # i don't like labels, so in fact the only value taken is the size of the array
  @@MONTHS = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", 'Junio', 'Julio',
            'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre']

  attr_accessor :title
  
  def initialize(year, file)
    @year = year
    @f = File.open(file, 'r')
    move_to_data
  end
  
  def days_of_month(month)
    start_period = Date.strptime(date_str(1, month), DATE_FORMAT)
    end_period = Date.strptime(date_str(1, month + 1), DATE_FORMAT)
    (end_period -start_period).to_i
  end
  
  def parse_data
    @data = [] 
    for i in (1..@@MONTHS.size) do
      month_data = []
      days_of_month(i).times do
        month_data << read_int_line
      end
      @data << month_data
    end
    @f.close
  end
  
  def create_chart(name = 'graph.png')
    g = Gruff::Bar.new
    g.title = title || 'Visitas por mes'
    for i in 1..@data.size do
      g.data(@@MONTHS[i-1], @data[i-1].inject(0){|sum, n| sum + n})
    end
    g.minimum_value = 0
    g.y_axis_increment = 500
    g.legend_font_size = 10
    g.legend_box_size = 10
    g.y_axis_label = 'Visitas'
    g.x_axis_label = round
    g.write(name)
  end

  def round
    if @data then
      total = 0
      for i in (1..@data.size)
        total = @data[i-1].inject(total){|sum, n| sum + n}
      end
      return "Visits per month: #{total / 12} \n" + 
             "Visits per day: #{total / 365}\n"
    else
      "You have to parse the data first"
    end
  end
    
  private
  def date_str(day, month)
    if month >= 1 and month <= 12
      "#{day}/#{month}/#{@year}"
    elsif month > 12
      "#{day}/#{(((month-1) % 12)+1)}/#{(@year + (month/12))}"
    else
      raise 'mes invalido'
    end
  end
  
  def read_int_line
    raise "formato del fichero invalido" if (@buff =~ /^\d+\n$/).nil?
    value = @buff.to_i
    @buff = @f.readline
    value
  end
  
  def move_to_data
    found = false
    while not found
      raise "formato del fichero inválido" if @f.eof?
      @buff = @f.readline
      found = (@buff =~ /^\d+\n$/) != nil
    end
  end
end

if ARGV.size == 0
  puts "You have to give the name of the csv file exported from google analytics"
  exit
end
################################################################################
# main body
################################################################################
parser = GoogleAnalyticsCsvParser.new(2007, ARGV[0])
parser.title = ARGV[1] if (ARGV[1])
parser.parse_data
parser.create_chart
puts "#grafico creado"
puts parser.round
