# -*- coding: utf-8 -*-
# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.

class ApplicationController < ActionController::Base
  include AuthenticatedSystem
  include MobileAuthenticatedSystem
  trans_sid

  rescue_from ActiveRecord::RecordNotFound do |exception|
    render :json => Comm::Tool::Json.result_json(false, EMD0003), :status => :not_found
  end

  helper :all # include all helpers, all the time
  protect_from_forgery # See ActionController::RequestForgeryProtection for details

  before_filter :set_charset, :login_required
  after_filter :check_read_auth
  
  # Scrub sensitive parameters from your log
  # filter_parameter_logging :password
  private
  # [tohki] 携帯の場合は XHTML Content-Type を出力する
  def set_charset
    if request.mobile?
      headers["Content-type"] = "application/xhtml+xml; charset=UTF-8"
    else
      headers["Content-type"] = "text/html; charset=UTF-8"
    end
  end
  
  def check_read_auth
    #menuのnameをコントローラ名から取得する
    menu_name = self.class.to_s.sub("Controller", "").underscore.gsub("/","_")
    ar = Menu.find_by_sql("SELECT id FROM menus WHERE name='#{menu_name}'").first
    role_ids = RolesUser.sassign('user_id', session[:user_id]).all.map{|r| r.role_id}
    #該当するメニューがあれば、アクセス制御する。ない場合は、アクセス制御しない。
    unless ar.blank?
      #メニューをみてチェックする
      if check_menu_auth(ar, role_ids)
        return true
      end
      # 管理者権限を持っているかチェック
      if role_ids.include?(ROLE_ADMIN_ID)
        return true
      end
      #上記すべてだめだった場合はログイン画面にもどるかトップに戻る。
      if menu_name=='top' || menu_name=='mobile_top'
        access_denied
      else
        if params[:action] == "ext_index" && menu_name==params[:controller]
          erase_render_results #レンダーをキャンセル
          render :json => [].ext_hashfy.to_ext_json(params[:controller], 0)
        elsif params[:action] == "summary"
          ar = Menu.find_by_sql("SELECT id FROM menus WHERE name='my_home_portlet'").first
          unless ar.blank?
            if check_menu_auth(ar, role_ids)
              return true
            end
          end
          erase_render_results #レンダーをキャンセル
          render :json => {'all'=>[],'area'=>[], 'user'=>[], 'sales_areas'=>[]}
        elsif params[:action] == "child"
          ar = Menu.find_by_sql("SELECT id FROM menus WHERE name='#{params[:controller].gsub("_details","").pluralize()}'").first
          unless ar.blank?
            if check_menu_auth(ar, role_ids)
              return true
            end
          end
          erase_render_results #レンダーをキャンセル
          render :json => {'results'=>false, params[:controller] => []}
        else
          redirect_to :controller => '/top', :action => 'index'
        end
      end
    end
  end
  
  def check_menu_auth(ar, role_ids)
      menu_id = ar.id
      # roles_menusをチェック
      unless role_ids.blank?
        role_ar = RolesMenu.find_by_sql("SELECT auth_code FROM roles_menus WHERE menu_id=#{menu_id} AND role_id IN (#{role_ids.join(',')}) AND auth_code > 0")
        unless role_ar.blank?
          return true
        end
      end
      # users_menusをチェック
      user_ar = UsersMenu.find_by_sql("SELECT auth_code FROM users_menus WHERE menu_id=#{menu_id} AND user_id=#{session[:user_id]} AND auth_code > 0")
      unless user_ar.blank?
        return true
      end
  end
end
