require "rss"
class CustomAnnouncementFeedsController < ApplicationController
	include Admin::CustomAnnouncementsHelper
	def feed
		uid = params[:uid]
		feed_cache = CustomBulletinFeedCache.where(uid: uid).first
		custom_anns = ''
		if feed_cache.nil?
			CustomBulletinFeedCache.create(uid: uid,content: '')
			Thread.new do
				custom_anns = get_custom_announcements(uid).to_json
				feed_cache = CustomBulletinFeedCache.where(uid: uid).first
				if !feed_cache.nil?
					feed_cache.update_attributes(content: custom_anns)
				end
			end
		else
			custom_anns = feed_cache.content
		end
		render :json => custom_anns
	end

	def rssfeed
		uid = params[:uid]
		@bf = CustomBulletinFeed.find_by(:uid => uid) rescue nil
		if !@bf.nil?
			tags = @bf.tag_ids
			if !tags.empty?
				@custom_announcements = CustomBulletin.can_display_and_sorted.is_approved.filter_by_tags(tags)
			end
		end
		respond_to do |format|
			format.html {redirect_to "/xhr/custom_announcements/rssfeed/#{@bf.uid}.rss"}
			format.rss
		end
	end

	def feeds
		feeds = []
		CustomBulletinFeed.all.each do |bf|
			feed = {}
			feed["title_translations"] = bf.title_translations
			feed["uid"] = bf.uid
			feed["url"] = "#{request.base_url}/xhr/custom_announcements/feed/#{bf.uid}"
			feed["xml_url"] = "#{request.base_url}/xhr/custom_announcements/rssfeed/#{bf.uid}.rss"
			feed["tags"] = []
			bf.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

	private 

	def smart_convertor(text)
		html_string = text
	  url = request.protocol + request.host_with_port
	  html_string = html_string.gsub(/img.*?src="(?=\/)(.*?)|a.*?href="(?=\/)(.*?)/i){|w| w+url}
	  html_string = html_string.gsub(/img.*?src="\.\.(?=\/)(.*?)|a.*?href="\.\.(?=\/)(.*?)/i){|w| w[0...-2]+url}
	  return html_string
	end

	def get_custom_announcements(uid)
		bf = CustomBulletinFeed.find_by(:uid => uid) rescue nil
		startdt = params[:start]
		enddt = params[:end]
		dt = params[:date]
		if !bf.nil?
			tags = bf.tag_ids
			if !tags.empty?
				if !dt.nil?
					dt = DateTime.parse(dt)
					dtt = dt + 1.day
					custom_announcements = CustomBulletin.where(:postdate.gt => dt, :postdate.lt => dtt).can_display_and_sorted.is_approved.filter_by_tags(tags)
				elsif !startdt.nil? && enddt.nil?
					startdt = DateTime.parse(startdt)
					enddt = DateTime.now
					custom_announcements = CustomBulletin.where(:postdate.gt => startdt, :postdate.lt => enddt).can_display_and_sorted.is_approved.filter_by_tags(tags)
				elsif !startdt.nil? && !enddt.nil?
					startdt = DateTime.parse(startdt)
					enddt = DateTime.parse(enddt) + 1.day
					custom_announcements = CustomBulletin.where(:postdate.gt => startdt, :postdate.lt => enddt).can_display_and_sorted.is_approved.filter_by_tags(tags)
				else
					custom_announcements = CustomBulletin.all.can_display_and_sorted.is_approved.filter_by_tags(tags)
				end
			else
				custom_announcements = []
			end
		end
		all_custom_anns = []
		tag_names = []
		tag_ids = []
		custom_announcements.each do |custom_anns|
			user = User.find(custom_anns.create_user_id) rescue nil
			if !user.nil?
				author = user.member_profile && user.member_profile.name == "" ? user.user_name : user.member_profile.name
			else
				author = ""
			end
			a = {}
			a["id"] = custom_anns.uid
			a["title_translations"] = custom_anns.title_translations
			a["subtitle_translations"] = custom_anns.subtitle_translations
			a["text_translations"] = {}
			a["text_translations"]["en"] = smart_convertor(custom_anns.text_translations["en"]) if !custom_anns.text_translations["en"].blank?
			a["text_translations"]["zh_tw"] = smart_convertor(custom_anns.text_translations["zh_tw"]) if !custom_anns.text_translations["zh_tw"].blank?
			a["postdate"] = custom_anns.postdate
			a["image_description_translations"] = custom_anns.image_description_translations
			a["image"] = {}
			a["display_img"] = custom_anns.display_img
			a["image"]["original"] = ("#{request.base_url}" + custom_anns.image.url rescue "")
			a["image"]["thumb"] = ("#{request.base_url}" + custom_anns.image.thumb.url rescue "")
			a["image"]["mobile"] = ("#{request.base_url}" + custom_anns.image.mobile.url rescue "")
			a["tags"] = []
			a["author"] = author
			a["params"] = custom_anns.to_param
			a["subtitle_ann"] = custom_anns.subtitle if custom_anns.display_subtitle?
			a["custom_bulletin_links"] = []
			a["custom_bulletin_files"] = []
			a["custom_bulletin_carousel_images"] = custom_anns.custom_bulletin_carousel_images.map{|image| {"src"=>"#{request.base_url}" + image.file.url,"description"=>image.description.to_s,"description_text"=>image.description_text }}
			custom_anns.tags.each do |tag|
				if !tag_ids.include?(tag.id.to_s)
					tag_ids << tag.id.to_s
					tag_names << {"name_translations" => tag.name_translations}
				end
				a["tags"] << {"name_translations" => tag.name_translations}
			end
			custom_anns.custom_bulletin_links.each do |bl|
				b = {}
				b["url"] = bl.url
				b["title_translations"] = bl.title_translations
				a["custom_bulletin_links"] << b
			end
			custom_anns.custom_bulletin_files.each do |bf|
				b = {}
				b["description_translations"] = bf.description_translations
				b["title_translations"] = bf.title_translations
				b["url"] = ("#{request.base_url}" + bf.file.url rescue "")
				a["custom_bulletin_files"] << b
			end
			all_custom_anns << a
		end
		{
			"custom_announcements" => all_custom_anns,
			"tags" => tag_names
		}
	end
end