class SiteController < ApplicationController

  before_action :set_locale

  def index
    @node = Node.roots.viewable.first
    not_found and return unless @node

    render(template: "site/#{@node.template}")
  end


  def page
    @node = Node.find_by!("url->>'#{I18n.locale}' = ?", url_from_param)

    not_found and return unless (@node and @node.viewable?)

    # Redirect to first child if index?
    redirect_to @node.children.viewable.ordered.first.url and return if @node.index? and @node.children.viewable.any?

    # Link or render
    redirect_to(@node.href, allow_other_host: true) and return if @node.href.present?

    render(template: "site/#{@node.template}")
  end


private

  def url_from_param
    return '' unless params[:url]

    # return File.join('', params[:url]) if I18n.default_locale == I18n.locale
    File.join('', I18n.locale.to_s, params[:url])
  end

end
