class LoginsInfoController < ApplicationController
  before_filter :check_access, :set_locale 
  def index
  end

  def edit
      @login=Login.select(:id,:name,:full_name,:department,:email,:office_id,:phone,:mobile_phone).find(params[:id])
  end

  def update
      @login=Login.find(params[:id])
      photo_dir="app/assets/images/logins_photo/"
      if params[:login][:photo].blank? == false
		  image=File.file?("app/assets/images/logins_photo/#{@login.name}.png")
		  image_jpg=File.file?("app/assets/images/logins_photo/#{@login.name}.jpg")
		  if image == true; FileUtils.rm("app/assets/images/logins_photo/#{@login.name}.png");end
          if image_jpg == true; FileUtils.rm("app/assets/images/logins_photo/#{@login.name}.jpg");end
          image_path="#{photo_dir}/#{@login.name}.#{params[:login][:photo].path.split('.')[-1]}"
          File.open(image_path,"wb") do |f|
               f.write(params[:login][:photo].read)
          end
      end
      update_info=params[:login]
      @login.update(
          :full_name => update_info[:full_name], 
          :department => update_info[:department], 
          :email => update_info[:email], 
          :office_id => update_info[:office_id], 
          :phone => update_info[:phone], 
          :mobile_phone => update_info[:mobile_phone]
      )
      redirect_to settings_logins_info_index_path
  end

  def show
      @login_info=Login.joins(:office)\
          .select(
              :id,
              :name,
              :full_name,
              :department,
              :email,
              '"offices"."name" as office_name',
              :phone,
              :mobile_phone
          ).find(params[:id])
      if $active_db == "sqlserver"
          count_per_day="COUNT(DISTINCT(CONVERT (date,end_time,104)))"
      else
          count_per_day="COUNT(DISTINCT(end_time::date))"
      end
      
      @all_user_activity=[]
      check_null_user_time_avg='CASE WHEN (user_time_avg > 0) THEN user_time_avg ELSE 1 END'
      @login_week_activity=ActiveDatum.global_filter(session[:user_id])\
          .time_part_group('day week','end_time').select("(COUNT(operation_id)/#{count_per_day})/(SUM(user_time/3600)/#{count_per_day}) as busy")\
          .where(:login_id => params[:id]).joins(:operation)\
          .select(
              "coalesce(SUM(CASE WHEN (user_time/#{check_null_user_time_avg}) <= 1 THEN 1 ELSE 0 END),0) as green",
			  "coalesce(SUM(CASE WHEN (user_time/#{check_null_user_time_avg}) > 1 and (user_time/user_time_avg) <= kpi THEN 1 ELSE 0 END),0) as yellow",
			  "coalesce(SUM(CASE WHEN (user_time/#{check_null_user_time_avg}) > kpi THEN 1 ELSE 0 END),0) as red"
          )
      #@all_logins_week_activity=ActiveDatum.global_filter(session[:user_id])\
      #    .time_part_group('day week','end_time').select("(COUNT(operation_id)/#{count_per_day})/(SUM(duration/3600)/#{count_per_day}) as busy_all")
      #@all_logins_week_activity.each do |day|
      #        @all_user_activity.push({:dow => ((day[:dow].to_i - 0.5) < 0 ? -0.5 : (day[:dow].to_i - 0.5)), :busy_all => day[:busy_all]})
      #        @all_user_activity.push({:dow => ((day[:dow].to_i + 0.5) > 6 ? 6.5 : (day[:dow].to_i + 0.5)) , :busy_all => day[:busy_all]})
      #        @all_user_activity.push({:dow => day[:dow].to_i, :busy_all => day[:busy_all]})
      #end
      @rating_array={:rating => 0, :count => 0, :red => 0, :yellow => 0, :green => 0}
      @login_week_activity.each do |day|
          @rating_array[:red]+=day[:red]
          @rating_array[:yellow]+=day[:yellow]
          @rating_array[:green]+=day[:green]
          @rating_array[:count]+=day[:red] + day[:yellow] + day[:green]
      end
      operation_weight=200.to_f/(@rating_array[:count] == 0 ? 1 : @rating_array[:count])
      
      absolute_rating=@rating_array[:green] * (operation_weight) + @rating_array[:yellow] * (operation_weight/2)
      @rating_array[:rating]= (((1000 *  absolute_rating) / 200).to_i.to_f)/100
  end
  def get_login_detailed_info
      login_day_activity=ActiveDatum.global_filter(session[:user_id]).joins(:operation)\
  	  .time_select('all')\
  	  .select(
        'COUNT(DISTINCT(operation_id)) as unique_oper',
  		'COUNT(operation_id) as count'
  	  ).where(:login_id => params[:id]).perfomance_data('count') 
      if params[:time_type].to_i == 1
            login_day_activity=login_day_activity.group_by_date
            order_date="date;#{params[:order].split(';')[1]}"
      elsif params[:time_type].to_i == 2
            login_day_activity=login_day_activity.time_part_group('week','end_time').time_part_group('year','end_time')
            order_date="year;#{params[:order].split(';')[1]},week;#{params[:order].split(';')[1]}"
      elsif params[:time_type].to_i == 3
            login_day_activity=login_day_activity.time_part_group('month','end_time').time_part_group('year','end_time')
            order_date="year;#{params[:order].split(';')[1]},month;#{params[:order].split(';')[1]}"
      end
    
    
      puts order_date
      if params[:order].split(';')[0] == 'date'
          order=order_date
      else
          order=params[:order]
      end
          
      
      gt_table_export(params[:export],login_day_activity,params[:headers]) && return
    render :text=> 	{:data => format_array_for_table(login_day_activity,order,params[:page],params[:offset]), :count => login_day_activity.length}.to_json
  end
  
  def get_login_list
    check_null_user_time_avg='CASE WHEN (user_time_avg > 0) THEN user_time_avg ELSE 1 END'  
    perfomance_array=ActiveDatum.global_filter(session[:user_id]).joins(:operation)\
          .select(
              "coalesce(SUM(CASE WHEN (user_time/#{check_null_user_time_avg}) <= 1 THEN 1 ELSE 0 END),0) as green",
		      "coalesce(SUM(CASE WHEN (user_time/#{check_null_user_time_avg}) > 1 and (user_time/user_time_avg) <= kpi THEN 1 ELSE 0 END),0) as yellow",
		      "coalesce(SUM(CASE WHEN (user_time/#{check_null_user_time_avg}) > kpi THEN 1 ELSE 0 END),0) as red",
              :login_id,
              'COUNT(operation_id) as count'
          ).group(:login_id)
    rating_array=[]
    perfomance_array.each do |login|
        operation_weight=200.to_f/(login[:count] == 0 ? 1 : login[:count])
        absolute_rating=login[:green] * (operation_weight) + login[:yellow] * (operation_weight/2)
        relative_rating= (((1000 *  absolute_rating) / 200).to_i.to_f)/100
        rating_array.push({:rating => relative_rating, :id => login[:login_id]})
    end    
	table_array = Login.joins(:office).select(:id,:name,:full_name,:department,:email,'"offices"."name" as office_name') 
    output_array=[]
    table_array.each do |login|
        rating=0
        rating_array.each do |login_rating|
            if login[:id] == login_rating[:id]
                rating=login_rating[:rating]
            end
        end
        member=login.as_json
        member["rating"]=rating
        output_array.push(member)
    end
    puts output_array
    gt_table_export(params[:export],output_array,params[:headers]) && return
  	render :text=> 	{:data => format_array_for_table(output_array,params[:order],params[:page],params[:offset]), :count => output_array.length}.to_json
  end
end
