class ArticlesController < ApplicationController
	# Find the article based on the id
	before_action :find_article, only: [:show, :edit, :update, :destroy]
	# Guests can not create, delete or edit articles
	before_action :authenticate_user!, except: [:index, :show]

	# Show the list of all the articles and sort them by their creation time
	def index
		@articles = Article.all.order("created_at DESC")
	end

	# Show the current article id at the route /articles/{:id}
	def show
		@article = Article.find(params[:id])
	end

	# Create a new article
	def new
		@article = current_user.articles.build
	end

	# Create a new article using the article params
	def create
		@article = current_user.articles.build(article_params)
		# If the article saves successfully redirect to the article path
		if @article.save
			flash[:notice] = "New article created successfully!"
			redirect_to @article
		else
		# If it doesn't saves return the new article view once again
			render 'new'
		end
	end

	private
		# Define the article params allowed at the creation of it
		def article_params
			params.require(:article).permit(:title, :body, :description, :header)
		end

		def find_article
			@article = Article.find(params[:id])
		end
end
