class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  rescue_from StandardError do |exception|
      new_logger = Logger.new('log/exceptions.log')
      new_logger_backtrace = Logger.new('log/exceptions_backtrace.log')
      new_logger.info('----------------- ОШИБКА -----------------')
      new_logger.info(exception.message)
      new_logger_backtrace.info('----------------- ОШИБКА -----------------')
      new_logger_backtrace.info(exception.message)
      new_logger_backtrace.info(exception.backtrace)
      render  :status => 500, :text => "#{exception.message.html_safe} <br> Контроллер - #{params[:controller]}"
  end
  
  
  def format_array_for_table(array,order,page,offset)
      order.split(',').each do |order_count| 
          order_field=order_count.split(';')[0]
          if order_count.split(';')[1] == 'ASC'
              @result=array.sort{|a,b| check_variable_for_nil(a[order_field]) <=> check_variable_for_nil(b[order_field])}
          else
              @result=array.sort{|a,b| check_variable_for_nil(b[order_field]) <=> check_variable_for_nil(a[order_field])}
          end
      end
      page_offset=(page.to_f-1)*offset.to_f
      return @result[page_offset..(page_offset+offset.to_f-1)]
  end
  
  def check_access
     user_post_loging  
     if session[:user_id] != nil && controller_access
        check_user_session_last_login()
        return true
     elsif session[:user_id] != nil
        check_user_session_last_login()
        redirect_to "/common/index"
     else
         if request.method == 'GET'
             redirect_to :controller => 'sessions', :action => 'login', :target => request.fullpath
         else
             redirect_to :controller => 'sessions', :action => 'login'
         end
     end
  end
  def set_locale
      I18n.locale = User.find(session[:user_id]).language || I18n.default_locale
  end
  def controller_access
      @controller_name=request.fullpath.split('/')[1]
      if @controller_name == 'common' || @controller_name == 'sessions' || @controller_name == nil
          return true
      end
      @controller_id=Menu.where(:name_eng => request.fullpath.split('/')[1]).first.id
      @access = UserAccess.where(:menu_id => @controller_id).where(:user_group_id => User.find(session[:user_id]).user_group_id).count > 0
      return @access
  end
  
  def check_global_filter(id)
      if GlobalFilter.where(:user_id => id).count == 0
          GlobalFilter.create(:user_id => id, :operation_source_id => 0, :operation_server_id => 0)
      end
  end
  
  def gt_table_export(check,data,headers)
      if check.to_i == 1
          head=[]
          body=[]
          JSON.parse(headers).each do |item|
              head.push(item["name"]);body.push(item["field"])
          end
   		  @header=head
   		  @body_data=body
   		  @array=data
          render xlsx: 'gt_export_form.xlsx', template: 'common/gt_export_form.xlsx', filename: "Sensor_#{params[:controller].capitalize}_Report.xlsx"
      end
  end
  def user_post_loging
      if request.post?
          UserLog.create(:user_id => session[:user_id], :action => request.path, :params => params, :ip => request.remote_ip, :action_type => 'POST')
      end
  end
  def check_user_session_last_login()
      user=User.find(session[:user_id])
      puts user.session_id == session[:login_id]
      puts session[:login_id]
      if user.session_id != session[:login_id]
          puts 1
          session[:user_id] = nil
          session[:session_id] = 0
          if request.method == 'GET'
              redirect_to :controller => 'sessions', :action => 'login', :target => request.fullpath
          else
              redirect_to :controller => 'sessions', :action => 'login'
          end
      end
      if user.last_login == nil ; 
          user.last_login = DateTime.now ; 
          user.save
      end
      if (user.last_login + 1.days) < DateTime.now
          puts 2
          session[:user_id] = nil
          session[:session_id] = 0
          if request.method == 'GET'
              redirect_to :controller => 'sessions', :action => 'login', :target => request.fullpath
          else
              redirect_to :controller => 'sessions', :action => 'login'
          end
      end 
      return true 
  end
  
  def check_variable_for_nil(field)
      if field == nil
          return ''
      else
          return field
      end
  end
end
