class CommonController < ApplicationController
    before_filter :check_access, :set_locale, :except => [:sensor_install]
  def index
  end
  
  def operation_sort
     oper_array=Operation.global_filter(session[:user_id]).joins(:operation_type,:operation_source)\
         .operation_name('name').select(
             :id, 
             '"operation_types"."name" as type_name',
             :color,
             :short_name
        )
     if $active_db == "sqlserver"
           oper_array=oper_array.where('lower("operations"."name") LIKE lower(?) OR lower(display_name) LIKE lower(?)',params[:string],params[:string])
     else
           oper_array=oper_array.where('lower("operations"."name") LIKE lower(?) = true OR lower(display_name) LIKE lower(?) = true',params[:string],params[:string])
     end
     render :text=> oper_array.to_json(:except => [ :created_at, :updated_at ])
  end
  def login_sort
     oper_array=Login.global_filter(session[:user_id])\
     .select(
        :id,
        '(CASE WHEN full_name IS NULL  OR full_name = \'\' THEN name ELSE full_name END) as name'
     )
     if $active_db == "sqlserver"
        result=oper_array.where('lower(name) LIKE lower(?) OR lower(full_name) LIKE lower(?)',params[:string],params[:string])
     else
        result=oper_array.where('lower(name) LIKE lower(?) = true OR lower(full_name) LIKE lower(?) = true',params[:string],params[:string])
     end
     render :text=> result.to_json(:except => [ :created_at, :updated_at ])
  end 
  def office_sort
     oper_array=Office.like_compare('name',params[:string],0).select(:name, :id)
     render :text=> oper_array.to_json(:except => [ :created_at, :updated_at ])
  end
  
  def get_errors_log
       send_file(Rails.root.join('log','exceptions.log'))
  end
  def get_errors_backtrace_log
       send_file(Rails.root.join('log','exceptions_backtrace.log'))
  end
  
  
  
  
  def get_index_graph
		output_array=[]
		source_array=ActiveDatum.global_filter(session[:user_id]).check_period(params[:start_time],params[:end_time])
		color_array=source_array.joins(:operation => :operation_type).perfomance_data('type')\
			.select(
				'COUNT(login_id) as count'
			)
			
		opers_hour_count=source_array.select(
				'COUNT(login_id) as "OperCount"'
				)\
				.time_part_group('hour','end_time')
				
		opers_top5=source_array.joins(:operation => :operation_type).select(
				'COUNT(login_id) as count'
				).operation_name('oper_name')\
				.operation_name_group.order('count DESC').limit(5)
		
		users_top5=source_array.joins(:login).login_name('loginname').select(
				'COUNT(operation_id) as count'
				).group('"logins"."name","logins"."full_name"').order('count DESC').limit(5)
		
		users_unique_by_hour=source_array.select(
				'COUNT(DISTINCT(login_id)) as count'
			).time_part_group('hour','end_time')
		
		opers_sys_time_compare=source_array.select(
				'SUM(sys_time)/SUM(duration) as sys_time',
				'SUM(user_time)/SUM(duration) as user_time'
			)
			
		office_top5=source_array.joins(:login => :office).select(
				'COUNT(operation_id) as count',
				'"offices"."name" as office_name'
				)\
				.group('"offices"."name"').order('count DESC').limit(5)
			
		office_sys_degrade=source_array.joins(:login => :office).select(
				'SUM(sys_time)/SUM(duration) as sys_time',
				'"offices"."name" as office_name'
				)\
				.group('"offices"."name"').order('sys_time DESC').limit(5)
		
		office_count_per_office=source_array.joins(:login => :office).select(
				'SUM(duration) as val',
				'"offices"."name" as arg'
				)\
				.group('"offices"."name"').order('val DESC')
		temp = request.env['HTTP_USER_AGENT']
		output_array={
			:color => color_array, 
			:oper_hour => opers_hour_count, 
			:oper_top5 => opers_top5, 
			:users_top5 => users_top5,
			:user_hour => users_unique_by_hour,
			:office_top5 => office_top5,
			:sys_compare => opers_sys_time_compare,
			:office_sys_degrade => office_sys_degrade,
			:office_count_per_office => office_count_per_office,
			:browser_list => temp
		}	
		render :text=> output_array.to_json(:except => [ :created_at, :updated_at ])
  end
  
  
  ################## скрипт инциализации #########################
  def sensor_install
      Menu.delete_all
      SubMenu.delete_all
      #if Menu.count == 0
          menu=Menu.create(:id => 1, :ru => 'Сотрудники',:en => 'Employees', :name_eng => 'logins')
              SubMenu.create(:id => 1, :ru => 'Производительность',:en => 'Performance', :name_eng => 'perfomance', :menu_id => menu.id, :visible => 1)
              SubMenu.create(:id => 2, :ru => 'Активность',:en => 'Activity', :name_eng => 'activity', :menu_id => menu.id, :visible => 1)
              SubMenu.create(:id => 3, :ru => 'Карта сотрудника',:en => 'Map', :name_eng => 'map', :menu_id => menu.id, :visible => 1)
              SubMenu.create(:id => 22, :ru => 'Статистика', :en => 'Statistics', :name_eng => 'statistic', :menu_id => menu.id, :visible => 1)    
          menu=Menu.create(:id => 2, :ru => 'Операции',:en => 'Operations', :name_eng => 'operations')
              SubMenu.create(:id => 5, :ru => 'Производительность', :en => 'Performance', :name_eng => 'perfomance', :menu_id => menu.id, :visible => 1)
              SubMenu.create(:id => 6, :ru => 'Активность',:en => 'Activity', :name_eng => 'activity', :menu_id => menu.id, :visible => 1)
              SubMenu.create(:id => 7, :ru => 'Карта операции',:en => 'Map', :name_eng => 'map', :menu_id => menu.id, :visible => 1)
             # SubMenu.create(:id => 8, :ru => 'Прогноз', :en => 'Forecast', :name_eng => 'prediction', :menu_id => menu.id, :visible => 1)
          menu=Menu.create(:id => 3, :ru => 'Филиалы',:en => 'Branches', :name_eng => 'office')
              SubMenu.create(:id => 9, :ru => 'Активность',:en => 'Activity', :name_eng => 'activity', :menu_id => menu.id, :visible => 1)
              SubMenu.create(:id => 21, :ru => 'Филиал',:en => 'Branch', :name_eng => 'list', :menu_id => menu.id, :visible => 1)
          menu=Menu.create(:id => 4, :ru => 'Статистика',:en => 'Statistics', :name_eng => 'statistic')
              SubMenu.create(:id => 10, :ru => 'Отчет', :en => 'Report', :name_eng => 'export', :menu_id => menu.id, :visible => 1)
              SubMenu.create(:id => 11, :ru => 'По операции', :en => 'By operation', :name_eng => 'operation', :menu_id => menu.id, :visible => 1)
              SubMenu.create(:id => 12, :ru => 'По дням', :en => 'By days', :name_eng => 'day', :menu_id => menu.id, :visible => 1)
              SubMenu.create(:id => 13, :ru => 'Сравнение дней', :en => 'Days compare', :name_eng => 'compare', :menu_id => menu.id, :visible => 1)
              SubMenu.create(:id => 20, :ru => 'Логирование Flextera', :en => 'Flextera Logs', :name_eng => 'flextera_log', :menu_id => menu.id, :visible => (params[:flextera_log] == nil ? 0 : 1))
          menu=Menu.create(:id => 5, :ru => 'Настройки',:en => 'Settings', :name_eng => 'settings')
              SubMenu.create(:id => 14, :ru => 'Оповещение по почте', :en => 'Email notifications', :name_eng => 'mail', :menu_id => menu.id, :visible => 1)
              SubMenu.create(:id => 15, :ru => 'Пользователи', :en => 'Users', :name_eng => 'users', :menu_id => menu.id, :visible => 1)
              SubMenu.create(:id => 16, :ru => 'Группы пользователей', :en => 'User groups', :name_eng => 'user_groups', :menu_id => menu.id, :visible => 1)
              SubMenu.create(:id => 17, :ru => 'Фильтры', :en => 'Filters', :name_eng => 'filters', :menu_id => menu.id, :visible => 1)
              SubMenu.create(:id => 18, :ru => 'Операции', :en => 'Operations', :name_eng => 'kpi', :menu_id => menu.id, :visible => 1)
              SubMenu.create(:id => 19, :ru => 'Сотрудники', :en => 'Employee information', :name_eng => 'logins_info', :menu_id => menu.id, :visible => 1)
              SubMenu.create(:id => 23, :ru => 'Active Directory', :en => 'Active Directory', :name_eng => 'ad_connections', :menu_id => menu.id, :visible => 1)
              SubMenu.create(:id => 24, :ru => 'Логирование', :en => 'Logs', :name_eng => 'logs', :menu_id => menu.id, :visible => 1)
     # end
      if Office.count == 0
          Office.create(:name => 'Центральный офис')
      end
      
      if User.count == 0
          user_group=UserGroup.create(:name_rus => 'Администраторы')
          user=User.create(
              :username => 'sensor', 
              :password => 'e7faa5b1531d1a756373fca131753f2749b401c1', 
              :salt => '792905a077cf88c8206df75e043485618dbb1b78', 
              :user_group_id => user_group.id,
              :from_date => DateTime.now,
              :to_date => DateTime.now
          )
          GlobalFilter.create(:user_id => user.id, :operation_server_id => 0, :operation_source_id => 0)
          
          OperationSource.create(:name => 'FA#', :color => '#27ae60', :short_name => 'FA#')
          OperationSource.create(:name => 'Flextera', :color => '#2980b9', :short_name => 'FT')
          Menu.all.each do |menu|
              UserAccess.create(:menu_id => menu[:id], :user_group_id => user_group.id)
          end
      end
      if LdapParameter.count == 0
          LdapParameter.create(:parameter => 'server', :name => 'Адрес сервера')
          LdapParameter.create(:parameter => 'port', :name => 'Порт')
          LdapParameter.create(:parameter => 'base', :name => 'Исходная точка подключения (base dn)')
          LdapParameter.create(:parameter => 'domain', :name => 'Домен')
      end
      if LdapUserGroup.count == 0
          UserGroup.order('id ASC').all.each_with_index do |group,index|
              LdapUserGroup.create(:user_group_id => group.id, :order_id => index)
          end
      end
      redirect_to '/common/index'
  end
  

end
