#!/usr/bin/env ruby

# Add the path to your feedcache directory here
FCPIPES_DIR = '/path/to/your/feedcache-pipes/plugin/directory'
# How many characters from each feed item do you want to display (only used if formatting feed titles)
CHAR_COUNT = 75
# Set to 'true' if you want to receive error emails from the CRON job
CRON_EMAILS = false


#################################################################
#                                                               #
#  DO NOT EDIT BELOW THIS LINE                                  #
#                                                               #
#################################################################
$LOAD_PATH << File.expand_path(File.dirname(__FILE__))

require 'net/http'
require 'lib/feedparser'
require 'uri'
require 'yaml'

# Read master config settings
MASTER_CONFIG = "#{FCPIPES_DIR}/master-config.txt"
cfg = File.open(MASTER_CONFIG, 'r') do |f|
  @params = f.gets.split('~');
end

# parse the parameters from the config file
@groups_num   = @params[0].strip.to_i
@display_num  = @params[1].strip
@format_text  = @params[2].strip == 'true' ? true : false
@link_target  = @params[3].strip == 'true' ? '_blank' : '_self'

# Load config and cache file variables
CONFIG_FILE = "#{FCPIPES_DIR}/files/fcpipes-config.yml"
CACHE_FILES = []
1.upto(@groups_num) do |i|
  CACHE_FILES << "#{FCPIPES_DIR}/files/fcpipes-cache#{i}.txt"
end

# RSS formatting function
def shorten_text(txt)
  if txt.size > CHAR_COUNT
    @text = "#{txt} ".slice(0,CHAR_COUNT)
    # need to break on the last space
    if @text.include?(' ') and @text.slice(@text.size-1, 1) != ' '
      @text.slice!(0, @text.size - (@text.reverse.index(' ') + 1))
      @text << '...'
    end
    return @text
  else
    return txt
  end
end

begin # read the config files settings
  @all_feeds = {}
  yaml_config = YAML.load_file(CONFIG_FILE)
  1.upto(@groups_num).each do |num|
    feeds = []
    next if yaml_config["group#{num}"].nil?
    yaml_config["group#{num}"].each { |x| feeds << x.strip if (!x.nil? && !x.strip.blank?) }
    @all_feeds[num] = feeds
    feeds = nil
  end
rescue => e
  if CRON_EMAILS
    puts "Error reading configuration file"
    puts YAML.dump(e)
  end
end  

@entry_groups = {}

# process the feed list
@all_feeds.each do |k, v|
  entries = {}
  # parse the feeds
  v.each do |feed|
    begin
      source = Net::HTTP::get URI::parse(feed)
      fp = FeedParser::Feed::new(source)
      fp.items.each do |item|
        entries[item.date.to_i] = item
      end
    rescue Exception => e
      if CRON_EMAILS
        puts "Error processing feed - #{feed}"
        puts YAML.dump(e)
      end
    end
  end
  @entry_groups[k] = entries
end #--> @all_feeds.each do |k,v|
  
# now process each group by timestamp
@entry_groups.each do |k,v|
  tmp = ''
  processed = false
  count = 1
  html_text = "<ul class='fcpipes'>"
  
  # sort entries by timestamp and process
  v.sort {|a,b| b[0]<=>a[0]}.each do |key, item|
    break if count > @display_num.to_i
    output = ''
    output << "<li><a href='#{item.link}' target='#{@link_target}'>"
    if @format_text
      txt = "#{ item.title.downcase.gsub(/^[a-z]|\s+[a-z]/) {|a| a.upcase} }"
      output << shorten_text(txt)
    else 
      output << "#{item.title}"
    end
    output << "</a></li>\n"
    html_text << output
    count += 1
  end
  
  html_text << "</ul><br />\n"
  tmp << html_text
  processed = true

  # if we had new feeds, move them to the cache file
  if processed
    cache = File::open(CACHE_FILES[k], "w")
    cache << tmp
    cache.close
  end
end # end @entry_groups.each do |k,v|
