require 'feed-normalizer'
require 'open-uri'

class SimpleCiController < ApplicationController
  layout 'base'
  before_filter :find_project, :authorize

  def show
    # Build the regular expression used to detect successfull builds
    success_re = Regexp.new(Setting.plugin_simple_ci['success_keyword'].strip, Regexp::IGNORECASE)
    # Find the project's CI RSS feed URL
    # This URL is stored in a 'regular' project custom field
    feed_url = @project.custom_values.detect {|v| v.custom_field_id == Setting.plugin_simple_ci['feed_url_custom_field'].to_i}
    feed_url = feed_url.value if feed_url
    if !feed_url.blank?
      begin
        content = ''
        # Open the feed and parse it
        rss = FeedNormalizer::FeedNormalizer.parse open(feed_url.strip)
        if rss
          @builds = rss.entries.collect do |item|
            build = {
              :time => item.date_published,
              :title => item.title,
              :description => item.description,
              :link => item.url
            }
            build[:success] = (success_re.match(item.title) ? true : false)
            build
          end
        else
          flash.now[:error] = 'Invalid RSS feed.' unless @builds
        end
      rescue SocketError
        flash.now[:error] = 'Unable to connect to remote host.'
      end
    @show_descriptions = Setting.plugin_simple_ci[:show_descriptions].to_i
    else
      flash.now[:error] = 'The feed URL is not defined for this project.'
    end
  end

private
  def find_project
    @project = Project.find(params[:id])
  rescue ActiveRecord::RecordNotFound
    render_404
  end
end

