require 'hpricot'
class InternetFirstController < ApplicationController
	
	layout "site"

	before_action :set_meta_tags

	def index
		
	end

	def edit_pillar_page
		
	end

	def show
		
	end

	def by_author
		@author = Author.where(:post_url => params[:author_url]).first
		if !@author.present?
			render :error, :layout => 'error', status: 404
		end
	end


	def articles
		ids = []
		@popular_articles = Article.where.not(:id => ids).where(:status => "Active").order(:priority => "ASC").limit(5)
		@popular_articles.each do |a| 
			ids.push(a.id)
		end
		@articles = Article.where.not(:id => ids).where(:status => "Active").paginate(:page => params[:page], :per_page => 9).order(:priority => "ASC")
		if @articles.count > 0
			@article = @articles.first
		end
		@articles.each do |article|
			puts article.title
		end
		@page = Page.where(:url => "blog").first
	end

	def article
		@article = Article.where(:post_url => params[:post_url]).where(:status => "Active").first
		@words = 0
		@articleBody = ""
		if @article.present? 
			@pillar = @article
			@articles = Article.where.not(:id => @article.id).where(:status => "Active").where(:category_id => @article.category_id).order("RAND()").limit(3)
      if @article.content.present? && !@article.content.nil?
      	doc = Hpricot(@article.content)
      	@articleBody = doc.inner_text
      	@words = doc.inner_text.split.count
      end
			render :article
		else
			render :error, :layout => 'error', status: 404
		end
			
	end

	def pillar
		if params[:post_url].present?
			@pillar = Pillar.where(:post_url => params[:post_url]).first
			if !@pillar.present?
				redirect_to "/blog"
			end
		else
			@pillar = Pillar.where(:post_url => 'internet-first').first
		end
	end

	

	private

		def set_meta_tags
			@meta_tags = MetaTag.where(:action_name => action_name).first
			if !@meta_tags.present?
				@meta_tags = MetaTag.where(:action_name => "home").first
			end

			#@articles = Article.where(:status => "Active").where("topics LIKE ?", "%"+@meta_tags.title.to_s+"%").limit(0)
		end
end