class SessionsController < ApplicationController
     before_filter :check_access, :set_locale, :except => [:login_attempt,:login,:logout] 
    def login
        I18n.locale = params[:locale] || I18n.default_locale
    end
    
    def login_attempt
      if params[:ad_auth_check].to_i == 0
          authorized_user = User.authenticate(params[:username],params[:login_password])
      else
          authorized_user = User.ad_auth(params[:username],params[:login_password])
      end

      if authorized_user
        session[:ad_selected]= params[:ad_auth_check].to_i == 0 ? false : true
        session[:user_id] = authorized_user.id
        session_id=Digest::SHA1.hexdigest("#{DateTime.now}#{rand(1..10000)}")
        session[:login_id] = session_id
        if authorized_user.login_count == nil ; authorized_user.login_count=0 ; end
        authorized_user.login_count+=1
        authorized_user.last_login=DateTime.now.strftime('%Y-%m-%d %H:%M:%S')
        authorized_user.session_id=session_id
        authorized_user.save
        if params[:target] == nil
            redirect_to :controller => 'common', :action => 'index'
        else
            redirect_to params[:target]
        end
      else
        render "login"	
      end
    end
    def logout
      session[:user_id] = nil
      session[:session_id] = 0
      redirect_to :action => 'login'
    end
    def change_language
        language=['ru','en']
        user=User.find(session[:user_id])
        user.update(:language => language[params[:lang].to_i])
        redirect_to :back
    end
    
    def update_user_dates
        user_id=params[:user_id]
        from_date=params[:from_date]
        to_date=params[:to_date]
        selected_user=User.find(user_id)
        selected_user.update(:from_date => from_date, :to_date => to_date)
        render :text => 'ok'
    end
    def update_global_filter
        user_id=session[:user_id]
        server_id=params[:server_id]
        source_id=params[:source_id]
        custom_filter_id=params[:custom_filter_id]
        selected_user=GlobalFilter.where(:user_id => user_id).first
        selected_user.update(:operation_server_id => server_id, :operation_source_id => source_id, :custom_filter_id => custom_filter_id)
        render :text => 'ok'
    end
    
end
