class ApplicationController < ActionController::Base
  protect_from_forgery

  include ParserFrontEnd, ParserBackEnd, ApplicationHelper
  
  layout :layout_by_resource
  
  helper :admin
  before_filter :set_locale, :set_site

  def set_current_user
    User.current = current_or_guest_user
  end

  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
  
  def auth_failed_in_backend
     #redirect_to admin_dashboards_url 
     redirect_to root_path
  end
  
  # Check if the current_user is admin,if not redirect
  def is_admin?
    current_or_guest_user.admin? ? true : auth_failed_in_backend
  end
  
  # def is_manager?
  #    @module_app.is_manager?(current_or_guest_user) || is_admin?
  # end
  
  # # Check if the current_user is admin
  # def is_member?
  #   if (current_user rescue false)
  #     return true
  #   end
  #   return false
  # end
  
  # def is_guest?
  #   if session[:guest_user_id]
  #     return true
  #   end
  #   return false
  # end
  
  def for_admin_only
    if is_admin?
      true
    else
    flash[:error] = t("access.denied.not_admin")
    auth_failed_in_backend
    end
  end
  
  def for_app_manager
    if is_manager?
      true
    else
      flash[:error] = t("access.denied.app.not_manager")
      auth_failed_in_backend
    end
  end
  
  def for_app_sub_manager
    if (@module_app.sub_managing_users.include?(current_or_guest_user) || is_manager?)
      true
    else
      flash[:error] = t("access.denied.app.not_sub_manager")
      auth_failed_in_backend
    end
  end

  def for_app_user
    if (@module_app.app_auth.auth_users.include?(current_or_guest_user) || for_app_sub_manager )
      true
    else
      flash[:error] = t("access.denied.app.not_authed_user")
      auth_failed_in_backend
    end
  end

  def check_object_premission(obj,title)
    flash[:error] = t("access.denied.object")
    auth_failed_in_backend unless (obj.get_object_auth_by_title(title).auth_users.include?(current_or_guest_user) || is_manager? || is_admin? )
  end
  
  # Render the page
  def render_page
    if @item
      respond_to do |format|
        format.html { render :text => parse_page_noko(@item), :layout => 'page_layout' }
        format.rss { render_main_rss }
      end
    else
      render :text => '404 Not Found'
    end
  end

  def render_share
    object_class = params[:model].classify.constantize
    @object = object_class.find(params[:id])
    module_app = ModuleApp.first(:conditions => {:key => params[:key]})
    @item = @object.share_item
    #@item = Item.where(module_app_id: module_app.id).all_of("tag" => {"$in" => [nil,'']},"category" => { "$in" => [nil,'']}).first
    #binding.pry
    @orig_url = "http://#{request.host_with_port}/#{@item.path}?id=#{@object.id}"
    render 'shared/render_share', :layout => false
  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_locales_default_head(@site.in_use_locales)
    @site_valid_locales = site_locales_default_head(@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
    Page.root
  end

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

  def site_locales_default_head(locales)
    if locales[0].eql? I18n.locale.to_s
      locales
    else
      a = Array.new(locales)
      shift_out = a.delete(I18n.locale.to_s)
      [shift_out] + a
    end
  end
    # called (once) when the user logs in, insert any code your application needs
    # to hand off from guest_user to current_user.
    def logging_in
      # For example:
      # guest_comments = guest_user.comments.all
      # guest_comments.each do |comment|
        # comment.user_id = current_user.id
        # comment.save
      # end
    end


  def render_main_rss
    ret = ''
    ret << "/panel/#{@item.module_app.key}/front_end/#{@item.app_frontend_url}.rss"
    ret << "/#{params[:id]}" if params[:id] && !params[:id].eql?(@item.id.to_s)
    ret << "?inner=true&category_id=#{params[:category]}&tag_id=#{params[:tag]}&page_main=#{params[:page_main]}"
    redirect_to ret
  end

end
