class PagesController < ApplicationController
  include ApplicationHelper
  before_filter :get_item, :only => [:index_from_link, :show_from_link]
  before_filter :check_frontend_open, :only => [:index,:show]
  # caches_page :index

  def check_frontend_open
    if Me.frontend_closed and current_user.nil?  #Need to be change
      redirect_to '/admin/dashboards'  
    end
  end

  def index
    @item = Page.find_by_name('home')

    if @item
      delayed_impressionist(@item)
      render_page 
    else
      redirect_to '/admin/dashboards',:notice=>t(:need_home)
      # render :text => t(:need_home)
    end
  end
  
  def show
    #begin  
      @item = Item.first(:conditions => {:path => params[:page_name]})
      if @item && @item.is_published && (@item.enabled_for.nil? ? true : @item.enabled_for.include?(I18n.locale.to_s))
        delayed_impressionist(@item)
        case @item.class.to_s
          when 'Page'
            if params[:clicked_field_name]
              render_page({"clicked_field_name"=>params["clicked_field_name"]}) unless save_from_no_lang_for_page
              else
              render_page(params) unless save_from_no_lang_for_page
            end
          when 'Link'
            redirect_to(@item[:url]) unless save_from_no_lang_for_page
        end
      else
        render :file => "#{Rails.root}/public/404.html", :status => :not_found
      end
    #rescue
    #  render :file => "#{Rails.root}/public/404.html", :status => :not_found
    #end
  end

  def index_from_link
    url = "/#{@item.path}"
    options = ''
    options << "#{options.blank? ? '?' : '&'}page_main=#{params[:page_main]}" unless params[:page_main].blank?
    options << "#{options.blank? ? '?' : '&'}#{convert_array_param('category_id', params[:category_id])}" unless params[:category_id].blank?
    options << "#{options.blank? ? '?' : '&'}#{convert_array_param('tag_id', params[:tag_id])}" unless params[:tag_id].blank?
    options << "#{options.blank? ? '?' : '&'}search_query=#{params[:search_query]}" unless params[:search_query].blank?
    options << "#{options.blank? ? '?' : '&'}name=#{params[:name]}" unless params[:name].blank?
    uri = URI::escape(url + options)
    #uri = URI::escape("#{url}?" + params.collect{|k,v| "#{k}=#{v}"}.join('&'))
    redirect_to(uri)unless save_from_no_lang_for_page
  end
   
  def show_from_link
    url = "/#{@item.path}"
    options = ''
    options << "#{options.blank? ? '?' : '&'}id=#{params[:id]}" unless params[:id].blank?
    options << "#{options.blank? ? '?' : '&'}#{convert_array_param('category_id', params[:category_id])}" unless params[:category_id].blank?
    options << "#{options.blank? ? '?' : '&'}#{convert_array_param('tag_id', params[:tag_id])}" unless params[:tag_id].blank?
    options << "#{options.blank? ? '?' : '&'}preview=#{params[:preview]}" unless params[:preview].blank?
    options << "#{options.blank? ? '?' : '&'}controller_action=#{params[:controller_action]}" unless params[:controller_action].blank?
    options << "#{options.blank? ? '?' : '&'}clicked_field_name=#{params[:clicked_field_name]}" unless params[:clicked_field_name].blank?
    redirect_to(url + options) unless save_from_no_lang_for_page
  end
   
  def load_orbit_bar
    render :partial => 'layouts/orbit_bar', :locals => {:referer => request.referer}
  end
   
  protected
   
  def get_item
    if params[:page_id]
      @item = Item.find(params[:page_id])
    elsif params[:same_page_id]
      @item = Item.find(params[:same_page_id])
    else
      category_ids = Array(params[:category_id]) unless params[:category_id].nil?
      tag_ids = Array(params[:tag_id]) unless params[:tag_id].nil?
      module_app = ModuleApp.first(:conditions => {:key => params[:app_name]})

      default_query = { is_published: true, module_app_id: module_app.id, :app_frontend_url.in => [params[:app_action], 'default_widget'] }
      specific_categories = { :category => category_ids }
      in_categories = { :category.in => category_ids }
      nil_categories = { :category.in => [nil, []] }
      specific_tags = { :tag => tag_ids }
      in_tags = { :tag.in => tag_ids }
      nil_tags = { :tag.in => [nil, []] }

      if !category_ids.blank? && !tag_ids.blank?
        @item = Item.where(default_query.merge(specific_categories).merge(specific_tags)).first
        @item = Item.where(default_query.merge(specific_categories).merge(in_tags)).first unless @item
        @item = Item.where(default_query.merge(specific_categories).merge(nil_tags)).first unless @item
        @item = Item.where(default_query.merge(specific_tags).merge(in_categories)).first unless @item
        @item = Item.where(default_query.merge(specific_tags).merge(nil_categories)).first unless @item
        @item = Item.where(default_query.merge(in_categories).merge(in_tags)).first unless @item
        @item = Item.where(default_query.merge(in_categories).merge(nil_tags)).first unless @item
        @item = Item.where(default_query.merge(in_tags).merge(nil_categories)).first unless @item
      elsif !category_ids.blank?
        @item = Item.where(default_query.merge(specific_categories).merge(nil_tags)).first
        @item = Item.where(default_query.merge(specific_categories)).first unless @item
        @item = Item.where(default_query.merge(in_categories).merge(nil_tags)).first unless @item
        @item = Item.where(default_query.merge(in_categories)).first unless @item
      elsif !tag_ids.blank?
        @item = Item.where(default_query.merge(specific_tags).merge(nil_categories)).first
        @item = Item.where(default_query.merge(specific_tags)).first unless @item
        @item = Item.where(default_query.merge(in_tags).merge(nil_categories)).first unless @item
        @item = Item.where(default_query.merge(in_tags)).first unless @item
      end
      @item = Item.find(params[:orig_page]) unless @item || params[:orig_page].blank?
      @item = Item.where(default_query.merge(nil_categories).merge(nil_tags)).first unless @item
      @item = Item.where(default_query).first unless @item
    end
    raise PageError, 'Missing Frontend Page' if @item.nil?
  end
  
  def save_from_no_lang_for_page
    if @item.nil? or !@item.enabled_for_lang(I18n.locale.to_s)
      flash[:error] = t('sys.module_page_lang_not_support')
      redirect_to '/'
      return true
    else
      return false
    end
  end
end