class SettingsController < ApplicationController
  before_filter :check_access, :set_locale  
  require 'open-uri'
  def mail
  end
  
  ######################### Mail Group #################################
  def mail_send_get_data
     last_id=params[:line_id].to_i
     if last_id.to_i == 0
        result_array={:last_id => ActiveDatum.global_filter(session[:user_id]).last[:id], :mailing => []}.to_json
     else
        output_data=[]
        check_data=ActiveDatum.global_filter(session[:user_id]).where('"active_data"."id" > ?',last_id)\
           .joins(:operation).joins(:login).operation_name('oper_name').select('user_time/user_time_avg as status', :kpi,:duration,:time_avg,'"logins"."name" as login_name', :end_time)\
           .where('user_time/user_time_avg > 1').order('status DESC')
        EmailRule.all.each do |rule|
           search_info=support_get_list(rule)
           if search_info[:operation_id][0] > 0
             check_data=check_data.where('operation_id IN (?)',search_info[:operation_id]) 
           end
           if search_info[:login_id][0] > 0
             check_data=check_data.where('login_id IN (?)',search_info[:login_id]) 
           end
           if search_info[:office_id][0] > 0
             check_data=check_data.where('office_id IN (?)',search_info[:office_id]) 
           end
           output_data.push({:mails => search_info[:mail], :data => check_data})
        end
        result_array={:last_id => ActiveDatum.global_filter(session[:user_id]).last[:id], :mailing => output_data}.to_json
     end
     render :text => result_array
  end
  def mail_add_new_rule
     #mails:[{"id":1,"mail":"testmail.ru"}]
     #operations:1
     #users:1
     #offices:1
     rule=EmailRule.create()
     JSON.parse(params[:mails]).each do |mail|
        EmailList.create(:email => mail["mail"], :email_rule_id => rule.id)
     end
     if params[:operations].to_i == 1
        EmailOperationList.create(:operation_id => 0, :email_rule_id => rule.id)
     else
        JSON.parse(params[:operations]).each do |foid|
           EmailOperationList.create(:operation_id => foid, :email_rule_id => rule.id)
        end
     end
     if params[:users].to_i == 1
        EmailLoginList.create(:login_id => 0, :email_rule_id => rule.id)
     else
        JSON.parse(params[:users]).each do |loginid|
           EmailLoginList.create(:login_id => loginid, :email_rule_id => rule.id)
        end
     end
     if params[:offices].to_i == 1
        EmailOfficeList.create(:office_id => 0, :email_rule_id => rule.id)
     else
        JSON.parse(params[:offices]).each do |officeid|
           EmailOfficeList.create(:office_id => officeid, :email_rule_id => rule.id)
        end
     end
     render :text => 'test'
  end
  def mail_get_rule_list
     rule_list=[]
     EmailRule.all.each do |rule|
        mail_list=[]
        foid_list=[]
        loginid_list=[]
        officeid_list=[]
        rule.email_lists.all.each do |mail|
           mail_list.push(mail[:email])
        end
        rule.email_operation_lists.all.each do |foid|
           foid_list.push(foid[:operation_id])
        end
        rule.email_login_lists.all.each do |loginid|
           loginid_list.push(loginid[:login_id])
        end
        rule.email_office_lists.all.each do |officeid|
           officeid_list.push(officeid[:office_id])
        end
        rule_list.push({:id => rule[:id] ,:mail => mail_list, :operation_id => foid_list, :login_id => loginid_list, :office_id => officeid_list})
     end
     render :text => rule_list.to_json
  end
  def mail_delete_rule
     rule=EmailRule.find(params[:id])
     rule.destroy
     render :text => 'test'
  end
  def mail_start_server
     port=params[:port]
     if RUBY_PLATFORM == "i386-mingw32"
         output = system "sensor_mailer\\mailer_start.bat #{port}"
     else
         puts RUBY_PLATFORM
         output = `cd sensor_mailer;nohup node index.js &>/dev/null &`
     end
     render :text =>  output
  end
  def mail_check_server

     response=''
     url = URI.parse('http://localhost:3010/mail_check')
     open(url) do |http|
       response = http.read
     end
     render :text => response
  end
  def mail_stop_server
     response=''
     url = URI.parse('http://localhost:3010/mail_stop')
     open(url) do |http|
       response = http.read
     end
     render :text => response
  end 
  def support_get_list(rule)
     mail_list=[]
     foid_list=[]
     loginid_list=[]
     officeid_list=[]
     rule.email_lists.all.each do |mail|
        mail_list.push(mail[:email])
     end
     rule.email_operation_lists.all.each do |foid|
        foid_list.push(foid[:operation_id])
     end
     rule.email_login_lists.all.each do |loginid|
        loginid_list.push(loginid[:login_id])
     end
     rule.email_office_lists.all.each do |officeid|
        officeid_list.push(officeid[:office_id])
     end
     return {:mail => mail_list, :operation_id => foid_list, :login_id => loginid_list, :office_id => officeid_list}
  end
  ################################# KPI ######################################
  def settings_get_kpi_list
      global_kpi=Operation.group(:kpi).select(:kpi,'COUNT(id) as count').order('SUM(id) DESC').first[:kpi]
      oper_list=Operation.global_filter(session[:user_id]).joins(:operation_type,:operation_source).operation_name('name')\
      .select(
          :id,
          :time_avg,
          :sys_time_avg,
          :user_time_avg,
          :kpi,
          :count_avg,
          :color,
          :short_name,
          '"operation_types"."name" as type_name',
          "(CASE WHEN kpi = #{global_kpi} THEN 1 ELSE 0 END) as kpi_global"
      )
      if params[:operation_id].to_i > 0
          oper_list=oper_list.where(:id => params[:operation_id])
      end
      gt_table_export(params[:export],oper_list,params[:headers]) && return    
      render :text => {
              :data => format_array_for_table(oper_list,params[:order],params[:page],params[:offset]), 
              :count => oper_list.length,
              :global_kpi => global_kpi
      }.to_json
      
  end
  def settings_update_kpi
      update_array=JSON.parse(params[:values])
      ActiveRecord::Base.transaction do
          update_array.each do |operation|
              oper=Operation.find(operation['id'])
              oper.update(
                  :time_avg => operation['time_avg'], 
                  :user_time_avg => operation['user_time_avg'], 
                  :sys_time_avg => operation['sys_time_avg'], 
                  :count_avg => operation['count_avg'], 
                  :kpi => operation['kpi']
              )
          end
      end
      render :text => 'ok'
      
  end
  ####################################### Логирование ######################################
  def settings_get_logs
      logs=UserLog.joins(:user).select(
          :username,
          :user_id,
          :action,
          :ip,
          :params,
          :action_type,
          :created_at
      )
      gt_table_export(params[:export],logs,params[:headers]) && return    
      render :text => {
              :data => format_array_for_table(logs,params[:order],params[:page],params[:offset]), 
              :count => logs.length
      }.to_json
  end
  
  ####################################### Настройка AD #############################
  def ad_connections
      if UserGroup.count != LdapUserGroup.count
          group_id='-1'
          LdapUserGroup.select(:user_group_id).each do |group|
              group_id+=",#{group.user_group_id}"
          end
          UserGroup.where("id NOT IN (#{group_id})").each do |group|
              LdapUserGroup.create(:user_group_id => group.id, :order_id => group.id)
          end
      end
  end
  def update_ad_settings
      ad_params=JSON.parse(params[:parameters])
      ad_groups=JSON.parse(params[:groups])
      ad_params.each do |param|
          parameter=LdapParameter.where(:parameter => param['parameter']).first
          parameter.update(:value => param['value'])
      end
      ad_groups.each do |group|
          group_id=LdapUserGroup.where(:user_group_id => group['user_group_id']).first
          group_id.update(:ldap_group_name => group['ldap_group_name'])
      end
      render :text => 'ok'
  end
end
