require "rss"
class ArchiveFeedsController < ApplicationController
	include Admin::ArchiveFilesHelper
	def feed_add_remote
		if params[:url].present?
			uid = params[:uid].to_s
			archive_file_feed = ArchiveFileFeed.where(uid: uid).first
			if !(archive_file_feed.remote_urls.include?(params[:url]))
				archive_file_feed.remote_urls << params[:url]
				archive_file_feed.save
			end
		end
		render :json => {success: true}
	end
	def feed_remove_remote
		if params[:url].present?
			uid = params[:uid].to_s
			archive_file_feed = ArchiveFileFeed.where(uid: uid).first
			if archive_file_feed.remote_urls.delete(params[:url])
				archive_file_feed.save
			end
		end
		render :json => {success: true}
	end
	def feed
		uid = params[:uid].to_s
		feed_cache = ArchiveFileFeedCache.where(uid: uid)
		feed_cache_old = feed_cache.last
		count = feed_cache.count
	    if count > 1
	      feed_cache.limit(count-1).destroy
	    end
	    feed_cache = feed_cache.first
		archive_content = ''
		if feed_cache.nil?
			archive_content = ArchiveFileFeed.where(uid: uid).first.generate_one_cache_timeout(base_url: request.base_url,timeout: 20)
			archive_content = (feed_cache_old.content rescue "") if archive_content.nil?
		else
			archive_content = feed_cache.content
		end
		render :json => archive_content
	end

	def rssfeed
		uid = params[:uid].to_s
		@aff = ArchiveFileFeed.find_by(:uid => uid) rescue nil
		if !@aff.nil?
			tags = @aff.tag_ids
			if !tags.empty?
				@archive_files = ArchiveFile.local_data.can_display_and_sorted.filter_by_tags(tags)
			else
				@archive_files = ArchiveFile.local_data.can_display_and_sorted
			end
			categories = @aff.category_ids
			if !categories.empty?
				@archive_files = @archive_files.filter_by_categories(categories)
			end
		end
		respond_to do |format|
			format.html {redirect_to "/xhr/archive_files/rssfeed/#{@aff.uid}.rss"}
			format.rss
		end
	end

	def feeds
		feeds = []
		ArchiveFileFeed.all.each do |aff|
			feed = {}
			feed["title_translations"] = aff.title_translations
			feed["uid"] = aff.uid
			feed["url"] = "#{request.base_url}/xhr/archive_files/feed/#{aff.uid}"
			feed["xml_url"] = "#{request.base_url}/xhr/archive_files/rssfeed/#{aff.uid}.rss"
			feed["tags"] = []
			aff.tag_ids.each do |t|
				tag = Tag.find(t)
				d = {}
				d["name_translations"] = tag.name_translations
				feed["tags"] << d
			end
			feeds << feed
		end
		render :json => {"feeds" => feeds}.to_json
	end


end






