class LoginsController < ApplicationController
    before_filter :check_access, :set_locale
  def perfomance
  end

  def activity
  end

  def map
 	     @user=User.find(session[:user_id])
 	     if @user[:from_date] != @user[:to_date]
 		     redirect_to  :action=>'map_period', login_id: params[:login_id]
 	     end
  end
  
  def map_period
	     @user=User.find(session[:user_id])
	     if @user[:from_date] == @user[:to_date]
		     redirect_to  :action=>'map', login_id: params[:login_id] 
	     end
  end

  def statistic
  end
  
    ######### Users Perfomance ###################
  
  def get_user_perfomance
	source_array=ActiveDatum.global_filter(session[:user_id]).check_period(params[:start_time],params[:end_time])
	data=source_array.joins(:operation)\
		.group(:login_id).perfomance_data('count').time_select('all')\
		.select(
			'COUNT("active_data"."id") as count',
			:login_id
		)
	if params[:loginid].to_f > 0
		data=data.where(:login_id => params[:loginid])
    end
    logins=Login.joins(:office).login_name('login_name').select('"offices"."name" as office_name',:office_id,:id)
    table=[]
    detailed_info={:red => 0,:yellow => 0, :green => 0, :unique => data.length, :count => 0}
    data.each do |row|
        for i in 0..logins.length-1
            if logins[i][:id] == row[:login_id]
                table.push({
                    'login_name' => logins[i][:login_name],
                    'login_id' => row[:login_id],
                    'office_id' => logins[i][:office_id],
                    'office_name' => logins[i][:office_name],
                    'red' => row[:red],
                    'yellow' => row[:yellow],
                    'green' => row[:green],
                    'count' => row[:count],
                    'duration_sum' => row[:duration_sum],
                    'user_time_sum' => row[:user_time_sum],
                    'sys_time_sum' => row[:sys_time_sum]
                })
                detailed_info[:count]+=row[:count]
                detailed_info[:green]+=row[:green]
                detailed_info[:yellow]+=row[:yellow]
                detailed_info[:red]+=row[:red]
                i=logins.length
            end
        end
    end
    gt_table_export(params[:export],table,params[:headers]) && return
	render :text=> {
                        :data => format_array_for_table(table,params[:order],params[:page],params[:offset]), 
                        :count => data.length,
                        :detailed_info => detailed_info
                    }.to_json
  end
  
######### Users activity ###################
    def get_user_activity
	    source_array=ActiveDatum.global_filter(session[:user_id]).check_period(params[:start_time],params[:end_time])
	    data=source_array.perfomance_data('count')\
	        .group(:login_id).joins(:operation).joins(:login)\
            .select(
            'COUNT(operation_id) as count',			
            :login_id
            )
        if params[:foid].to_i > 0
            data=data.where(:operation_id => params[:foid].to_i)
        end
	    if params[:officeid].to_i > 0
	        data=data.where('"logins"."office_id" = ?',params[:officeid].to_i)
	    end
        
        result=[]
        logins=Login.joins(:office).login_name('login_name').select('"offices"."name" as office_name',:office_id,:id)
        data.each do |row|
            for i in 0..logins.length-1
                if logins[i][:id] == row[:login_id]
                    result.push({
                        'login_id' => logins[i][:id],
                        'login_name' => logins[i][:login_name],
                        'red' => row[:red],
                        'yellow' => row[:yellow],
                        'green' => row[:green],
                        'count' => row[:count],
                        'office_name' => logins[i][:office_name],
                        'office_id' => logins[i][:office_id]
                        
                    })
                    i=logins.length
                end
            end
        end
        gt_table_export(params[:export],result,params[:headers]) && return
	    render :text=> {
            :data => format_array_for_table(result,params[:order],params[:page],params[:offset]), 
            :count => result.length
        }.to_json
        
    end 
    def get_user_activity_graph_by_date
        source_array=ActiveDatum.global_filter(session[:user_id]).check_period(params[:start_time],params[:end_time])
        graph_array=source_array.joins(:login)\
        .group_by_date\
        .select(
            'COUNT(operation_id) as count'
        ).where(:login_id => params[:loginid])
        if params[:foid].to_i > 0
            graph_array=graph_array.where(:operation_id => params[:foid])
        end
        if params[:officeid].to_i > 0
            graph_array=graph_array.where('"logins"."office_id" = ?',params[:officeid].to_i)
        end
        render :text=> graph_array.to_json
    end 
    def get_user_activity_oper_top10
        source_array=ActiveDatum.global_filter(session[:user_id]).check_period(params[:start_time],params[:end_time])
        graph_array=source_array.joins(:operation => :operation_type)\
		.select(
			'COUNT(login_id) as count',
			'"operations"."name" as oper_name',
			:operation_id,
			'"operation_types"."name" as type_name'
			
		)\
		.group(:operation_id,'"operations"."name"','"operation_types"."name"').order('count DESC').limit(10)
        render :text=> graph_array.to_json
    end	
    def get_user_activity_office_top10
        source_array=ActiveDatum.global_filter(session[:user_id]).check_period(params[:start_time],params[:end_time])
        graph_array=source_array.joins(:login  => :office)\
		.select(
			'COUNT(operation_id) as count',
			'"offices"."name" as office_name',
			'"logins"."office_id" as office_id'
			
		)\
		.group(:office_id,'"offices"."name"').order('count DESC').limit(10)
	    render :text=> graph_array.to_json
    end	
   
 #######################################################################  
 def get_user_map
     output_array=[]
     source_array=ActiveDatum.global_filter(session[:user_id]).check_period(params[:start_time],params[:end_time])
     data=source_array.joins(:operation => :operation_type).joins(:operation => :operation_source).operation_name('oper_name').start_end_time().select(
        'user_time/user_time_avg as status',
        :kpi,
        :duration,
		'"operation_types"."name" as type_name',
		:user_time,
		:sys_time,
        :time_avg,
        :user_time_avg,
        :sys_time_avg,
		:id,
        :color,
        :module,
        :node,
        :short_name,
        :operation_id
	).where(:login_id => params[:Login_ID])
    systime=source_array.select(
		'SUM(sys_time)/SUM(duration) as percents'
	).where(:login_id => params[:Login_ID])
    graph=source_array.joins(:operation => :operation_type).start_end_time().operation_name('oper_name').select(
	    '"operation_types"."name" as type_name',
	    :user_time,
	    :sys_time,
		:id,
        :duration,
        :operation_id,
		'(CASE 	
            WHEN (user_time/user_time_avg) <= 1 THEN 1 
			WHEN (user_time/user_time_avg) > 1 and (user_time/user_time_avg) <= kpi THEN 2
			ELSE 3
		END) as status'
	).where(:login_id => params[:Login_ID]).order('end_time ASC')

    data_json=data.as_json
    count_oper=0
    full_time=0
    user_time=0
    sys_time=0
    opers=[]
    data_json.each do |item|
        count_oper+=1
        full_time+=item["duration"]
        user_time+=item["user_time"]
        sys_time+=item["sys_time"]
        opers.push({:oper => item["operation_id"], :name => item["oper_name"], :color => item["color"], :short_name => item["short_name"]})

    end
    opers=opers.uniq
    full_info={:full => full_time,:user => user_time, :sys => sys_time, :count => count_oper, :opers => opers.length, :opers_list => opers}
    gt_table_export(params[:export],data_json,params[:headers]) && return
    render :text=> {
            :count => data_json.length, 
            :data => format_array_for_table(data_json,params[:order],params[:page],params[:offset]), 
            :systime => systime, 
            :graph => graph, 
            :full_info => full_info
        }.to_json
 end 
 
######### Users compare ###################

    def get_user_compare_graph
	    source_array=ActiveDatum.global_filter(session[:user_id]).check_period(params[:start_time],params[:end_time])
	    graph_array=source_array.joins(:login).login_name('login_name')\
	    	.select(
	    		:login_id,
	    		'COUNT(operation_id) as count',
	    		'SUM(duration) as duration',
	    		'SUM(user_time) as user_time',
	    		'SUM(sys_time) as sys_time'	
	    	)\
	    	.group(:login_id,:full_name,'"logins"."name"').like_compare("'#{params[:loginid]}'",'concat(\'%,\',login_id,\',%\')',0)
            
        gt_table_export(params[:export],graph_array,params[:headers]) && return    
	    render :text=> {:data => format_array_for_table(graph_array,params[:order],params[:page],params[:offset]), :count => graph_array.length}.to_json

    end

################### User Map Period ######################
    def get_login_map_period_graph
        data = login_map_period_get_data(params[:login_id],params[:start_time],params[:end_time])
        render :text=> data.to_json
    end
    def get_login_map_period_table
		graph_array = login_map_period_get_data(params[:login_id],params[:start_time],params[:end_time]) 
        gt_table_export(params[:export],graph_array,params[:headers]) && return
    	render :text=> 	{:data => format_array_for_table(graph_array,params[:order],params[:page],params[:offset]), :count => graph_array.length}.to_json
    end


    
end



private

def login_map_period_get_data(id,start_time,end_time)
	source_array=ActiveDatum.global_filter(session[:user_id]).check_period(start_time,end_time)
	data=source_array\
	.group_by_date.time_select('all')\
	.select(
        'COUNT(DISTINCT(operation_id)) as unique_oper',
		'COUNT(operation_id) as logincount'
	)  
    if id.to_i > 0
        data=data.where(:login_id => id)
    end
    return data
end

