class ApplicationController < ActionController::Base
  protect_from_forgery
  
  include ParserFrontEnd, ParserBackEnd
  
  layout :layout_by_resource
  
  helper :all
  before_filter :set_locale, :set_site

  def front_end_available(module_app_title='')
    app_controller = ModuleApp.first(conditions: {:key => module_app_title} )
    unless app_controller.enable_frontend? 
      render :nothing => true
    end
  end
  
  def get_all_app_engines
    ary = ["vender/plugins/new_blog"]
    app_engines = ary.collect{|t|
      Rails::Engine.find t
    }
    app_engines.each{ |t|
     # t.
    }
  end

  def flaten_controller
    ary=[]
    Find.find(File.join(Rails.root , 'vendor/plugins/'))  { |name|  
          require_dependency(name) if /_controller\.rb$/ =~ name
          ary << name
    }
    ary
  end
  
  # Find the parent for the given item
  def find_parent_item
    @parent_item  = Item.first(:conditions => { :id => BSON::ObjectId(params[:parent_id]) }) rescue nil
  end
  
  # Check if the current_user is admin
  def is_admin?
    redirect_to root_url unless current_user.admin?
  end
  
  # Render the page
  def render_page(id = nil)
    if @item
      render :text => process_page(@item, id), :layout => 'page_layout'
    else
      render :text => '404 Not Found'
    end
  end
  
  protected
  
  # Set I18n.locale
  def set_locale
    # update session if passed
    session[:locale] = params[:locale] if params[:locale]

    # set locale based on session or default
    begin
      # check if locale is valid for non site pages
      if LIST[:forbidden_item_names].include?(env['PATH_INFO'].split('/')[1].to_s) && !VALID_LOCALES.include?(session[:locale])
        I18n.locale = I18n.default_locale
      else
        I18n.locale = session[:locale]
      end
    rescue
      I18n.locale = I18n.default_locale
    end    
  end
    
  # Set the site variables
  def set_site
    # set site if exist or create site
    @site = Site.first || Site.create({:valid_locales => [], :in_use_locales => []})
    session[:site] = @site.id
    @site_in_use_locales = @site.in_use_locales
    @site_valid_locales = @site.valid_locales
  end
  
  def set_current_item
    session[:current_page] = params[:id] || @item.id rescue nil
  end
  
  def decrypt_data(encrypted_data, encrypted_key, encrypted_iv)
    site = Site.find(session[:site])
    if encrypted_data
      private_key = OpenSSL::PKey::RSA.new(site.private_key)
      cipher = OpenSSL::Cipher.new('aes-256-cbc')
      cipher.decrypt
      cipher.key = private_key.private_decrypt(encrypted_key)
      cipher.iv = private_key.private_decrypt(encrypted_iv)

      decrypted_data = cipher.update(encrypted_data)
      decrypted_data << cipher.final
    else
      ''
    end
  end
  
  def get_homepage
    Item.first(:conditions => {:parent_id => nil})
  end

  def layout_by_resource
    if devise_controller?
      "devise"
    else
      "application"
    end
  end

end