class VisitorDetailsController < ApplicationController
  skip_before_action :verify_authenticity_token
  before_action :set_visitor_detail, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!, except: [:save_data]
  before_action :dashboard_topbar, except: [:save_data]

  # GET /visitor_details
  # GET /visitor_details.json
  def index
    @visitor_details = VisitorDetail.all
    respond_to do |format|
      format.html
      format.csv { send_data @visitor_details.to_csv }
    end
  end

  # GET /visitor_details/1
  # GET /visitor_details/1.json
  def show
  end

  # GET /visitor_details/new
  def new
    @visitor_detail = VisitorDetail.new
  end

  # GET /visitor_details/1/edit
  def edit
  end

  # POST /visitor_details
  # POST /visitor_details.json
  def create
    @visitor_detail = VisitorDetail.new(visitor_detail_params)

    respond_to do |format|
      if @visitor_detail.save
        flash[:success] = "Successfully created visitor detail"
        format.html { redirect_to @visitor_detail}
        format.json { render action: 'show', status: :created, location: @visitor_detail }
      else
        flash[:error] = "Oops! there was some problem in creating visitor detail"
        Rails.logger.warn "#{@visitor_detail.errors.full_messages}"
        format.html { render action: 'new' }
        format.json { render json: @visitor_detail.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /visitor_details/1
  # PATCH/PUT /visitor_details/1.json
  def update
    respond_to do |format|
      if @visitor_detail.update(visitor_detail_params)
        flash[:success] = "Successfully updated visitor detail"
        format.html { redirect_to @visitor_detail }
        format.json { head :no_content }
      else
        flash[:error] = "Oops! there was some problem in updating visitor detail"
        Rails.logger.warn "#{@visitor_detail.errors.full_messages}"
        format.html { render action: 'edit' }
        format.json { render json: @visitor_detail.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /visitor_details/1
  # DELETE /visitor_details/1.json
  def destroy
    if @visitor_detail.destroy
      flash[:success] = "Successfully deleted visitor detail"
    else
      flash[:error] = "Oops! there was some problem in deleting visitor detail "
      Rails.logger.warn "#{@visitor_detail.errors.full_messages}"
    end
    respond_to do |format|
      format.html { redirect_to visitor_details_url }
      format.json { head :no_content }
    end
  end

  def save_data
    unless params[:PRESENCE].blank?
      flash[:notice] = "Oops ! there was some problem in saving the scanned data"
      flash[:notice] = "Successfully scanned and saved the data!" if ScanningData.save_data(params[:PRESENCE])
    else
      flash[:notice] = "Data is empty!"
    end
    # ScanningData.save_data(params[:PRESENCE]) if params[:PRESENCE]
    render :json=> {:status=>false}
  end

  def dashboard
    get_dashboard
  end
  
  def get_dashboard
    params[:start_date] = 6.days.ago if params[:start_date].blank?
    params[:end_date]= 0.day.ago if params[:end_date].blank?
    @selected_date_range = params[:selected_date_range]
    @selected_date_range = "Last 7 Days" if params[:selected_date_range].blank?

    @aps = AclGroup.get_all_aps(@current_network)
    if params[:mac_ids].blank?
     @existing_aps = AclGroup.get_routers(@current_network)
    else
      ap_list =[]
      (params[:mac_ids].split("&&") || []).each do |x|
        next if x.blank?
        x = x.split("--")
        # ap_list << {"id"=>x[0].to_s+"--inventory", "name"=>x[2]}
        ap_list << {"id"=>x[0].to_s+"--"+x[1], "name"=>x[2]}
      end
      @existing_aps = ap_list
    end
    @startDate = params[:start_date];@endDate = params[:end_date]
    render :layout => "dashboard"
  end

  def change_network
    network = current_user.location_networks.find_by_id(params[:id])
    unless network.present?
    network = current_user.location_networks.first
    flash[:notice] = "Your network has been changed to #{network.network_name}"
    end
    current_user.current_network = network.id
    @current_network = current_user.current_network
    logger.info("Current Network in show <<<<<<#{@current_network.id}") unless @current_network.blank?
    redirect_to dashboard_visitor_details_path
  end

  def visitors_bar_chart
    render :json => VisitorDetail.visitors_bar_chart(location_ids(params[:rlid]),params[:start_date],params[:end_date], params[:offset])
  end

  def visitors_unique_return
    render :json => VisitorDetail.visitors_unique_return(location_ids(params[:rlid]),params[:start_date],params[:end_date], params[:offset])
  end

  def location_ids(loc_ids)
    mac_ids=[]
    loc_ids.split("&&").each do |x|
      x = x.split("--")
      if("tag".eql?(x[1]))
        @current_network.router_inventories.tagged_with(x[2]).each {|tag| mac_ids.push(tag.mac_id)}
      else
        mac_ids.push(x[2])
      end
    end
    return mac_ids.uniq
  end

  def avg_time_spend
    render :json => VisitorDetail.avg_time_spend(location_ids(params[:rlid]),params[:start_date],params[:end_date], params[:offset])
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    
    def set_visitor_detail
      @visitor_detail = VisitorDetail.where(:id => params[:id]).first
      if @visitor_detail.blank?
        flash[:warning] = "Requested Visitor Detail not found!"
        redirect_to visitor_details_url
      end
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def visitor_detail_params
      params.require(:visitor_detail).permit(:device_id, :mac_id)
    end
end
