class SessionsController < ApplicationController
  skip_before_action :authenticate, only: [:index, :show, :update, :create, :destroy]
  # Special check for only dashboard

  def index
    # @employees = Employee.all_emp_except_waiter.order("name asc")
    @employees = Employee.all.where("is_active = true").order("name asc")
    @roles = Employee.distinct.pluck(:role)
    # byebug
    # @roles = Lookup.collection_of("employee_roles")
    @login_form = LoginForm.new()
    render "layouts/login_dashboard", layout: false
  end

  def show
    @login_form = LoginForm.new()
    @login_form.emp_id = params[:emp_id]
    render "layouts/login", layout: false
  end

  def update
    @login_form = LoginForm.new()
    @login_form.emp_id = params[:emp_id]
    @login_form.password = params[:login_form][:password]
    @employee = Employee.login(@login_form.emp_id, @login_form.password)

    if @employee != nil
      session[:session_token] = @employee.token_session
      redirect_to root_path
    else
      flash[:notice] = "Invalid PIN for Employee. Please try again!"
      render :show
    end
  end

  def create
    @login_form = LoginForm.new(settings_home_params)
    @employee = Employee.login(@login_form.emp_id, @login_form.password)

    if @employee
      if @employee.is_active
        session[:session_token] = @employee.token_session
        redirect_to root_path
      else
        redirect_to login_path, :notice => "This Employee is not active"
      end
    else
      redirect_to login_path, :notice => "Username and Password doesn't match!"
    end
  end

  def destroy
    # clear in employee session
    Employee.logout(session[:session_token])
    session[:session_token] = nil
    # redirect_to root_path
    render :json => {:status=> "Success", :url => root_path }.to_json
  end

  def run_teamviewer
    if File.directory?("/opt/teamviewer")
      output = IO.popen('/opt/teamviewer/tv_bin/script/teamviewer')
      render :json => {:status=> true}
    else
      render :json => {:status=> false}
    end
  end

  private

  # Never trust parameters from the scary internet, only allow the white list through.
  def settings_home_params
    params.require(:login_form).permit(:emp_id, :password)
  end

end
