class FiltersController < ApplicationController
  before_filter :check_access, :set_locale  
  def index
      @filters=CustomFilter.all
  end

  def show
  end

  def new
  end

  def edit
  end
  
  def destroy
     user=CustomFilter.find(params[:id])
     user.destroy
     GlobalFilter.where(:custom_filter_id => params[:id]).update_all(custom_filter_id: 0)
     redirect_to settings_filters_path
  end
  
  def create
      operations=JSON.parse(params[:operations])
      logins=JSON.parse(params[:logins])
      filter_name = params[:name] == '' ? "Фильтр #{rand(1..10000)}" : params[:name]
      custom_filter = CustomFilter.create(:name => filter_name)
      ActiveRecord::Base.transaction do
          operations.each do |id|
              OperationFilter.create(:operation_id => id, :custom_filter_id => custom_filter.id)
          end
      end
      ActiveRecord::Base.transaction do
          logins.each do |id|
              LoginFilter.create(:login_id => id, :custom_filter_id => custom_filter.id)
          end
      end
      redirect_to settings_filters_path
  end
  
  def get_operations_to_filter
      operations=Operation.joins(:operation_type,:operation_source).operation_name('name').select(:id,:color,:short_name,'"operation_types"."name" as type_name')
      if params[:operation_id].to_i > 0
          operations=operations.where(:id => params[:operation_id])
      end
      if params[:operation_type_id].to_i > 0
          operations=operations.where(:operation_type_id => params[:operation_type_id])
      end
      if params[:operation_source_id].to_i > 0
          operations=operations.where(:operation_source_id => params[:operation_source_id])
      end
      render :text => operations.to_json
  end
  def get_logins_to_filter
      logins=Login.select(:id).login_name('name')
      if params[:login_id].to_i > 0
          logins=logins.where(:id => params[:login_id])
      end
      if params[:office_id].to_i > 0
          logins=logins.where(:office_id => params[:office_id])
      end
      render :text => logins.to_json
  end
  
  def update_filter
      operations=JSON.parse(params[:operations])
      logins=JSON.parse(params[:logins])
      filter_name = params[:name] == '' ? "Фильтр #{rand(1..10000)}" : params[:name]
      
      OperationFilter.where(:custom_filter_id => params[:id]).destroy_all
      LoginFilter.where(:custom_filter_id => params[:id]).destroy_all
      
      custom_filter=CustomFilter.find(params[:id])
      custom_filter.update(:name => filter_name)
      ActiveRecord::Base.transaction do
          operations.each do |id|
              OperationFilter.create(:operation_id => id, :custom_filter_id => custom_filter.id)
          end
      end
      ActiveRecord::Base.transaction do
          logins.each do |id|
              LoginFilter.create(:login_id => id, :custom_filter_id => custom_filter.id)
          end
      end
      redirect_to settings_filters_path
  end
  
end
