class Admin::TimerWatchersController < ApplicationController
  before_action :auth_admin
  
  def create
    params[:timer_watcher][:p_customer_id] = nil if params[:timer_watcher][:p_customer_id].to_s == ""
    
    params[:timer_watcher][:admin_space] = nil if params[:timer_watcher][:admin_space].to_s == ""
    
    if params[:timer_watcher][:element_type].to_s == "" 
      params[:timer_watcher][:element_type] = nil 
    else
      puts params[:timer_watcher][:element_type].size
    end
    
    params[:timer_watcher][:element_id] = nil if params[:timer_watcher][:element_id].to_s == ""
    start_at = Time.now
    time_end = Time.now + 6.second


    
    params_time= {:admin_id => current_admin.id, :p_customer_id => params[:timer_watcher][:p_customer_id], :admin_space => params[:timer_watcher][:admin_space], :element_type => params[:timer_watcher][:element_type], :element_id => params[:timer_watcher][:element_id] }
    
    @timer_watchers = TimerWatcher.where(params_time)

    @timer_watchers = @timer_watchers.where("end_at >= ?", (start_at-5.second)).order("end_at DESC")
    
    @last_timer_watcher = @timer_watchers.first
    
    if @last_timer_watcher
      @last_timer_watcher.end_at = time_end
      @last_timer_watcher.save
      
    else
      @timer_watcher = TimerWatcher.new(params_time)
      @timer_watcher.end_at = time_end
      @timer_watcher.save
    end 
    
    
    if false
      
      
  		@edit_watcher = EditWatcher.new(params.require(:timer_watcher).permit!)
    
      @edit_watcher.admin = current_admin
	
  		if @edit_watcher.save
      
  			@edit_watchers_source = EditWatcher.where("admin_id != ?", current_admin.id).where(:element_type => @edit_watcher.element_type, :element_id => @edit_watcher.element_id,:key => @edit_watcher.key)
		  
        @edit_wacthers_to_destroy = EditWatcher.where("created_at < ?", (Time.now - 2)).destroy_all
    
        @edit_watchers_source = @edit_watchers_source.where("created_at >= ?", (Time.now - 2)).group(:admin_id).all
    
    
		
  		end
      
      
    end
    
    render :inline => "ok"
  end
end
