class UsersController < ApplicationController
  skip_before_filter  :verify_authenticity_token 
  before_action :authenticate_member!
  before_action :set_user, only: [:show, :edit, :update, :destroy]

  # GET /users
  # GET /users.json
  def index
    @users = User.all.page(params[:page])
  end

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

  # GET /users/new
  def new
    @user = User.new
  end

  # GET /users/1/edit
  def edit
  end

  # POST /users
  # POST /users.json
  def create
    @user = User.new(user_params)
    email=params[:registered_email]
    @user.is_active=true
    # cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc")
    # key=cipher.random_key
    # secrect_key= Base64.encode64(key)
    # @user.secrect_key=secrect_key      
    @email=email
    respond_to do |format|
      if @user.save
        member_id= current_member.id
        member=Member.find_by_email(email)

        if !member.nil?
          member.user_id =@user.id
          member.save
        end

        format.html { redirect_to @user, notice: 'User was successfully created.' }
        format.json { render :show, status: :created, location: @user }
      else
        format.html { render :new }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /users/1
  # PATCH/PUT /users/1.json
  def update

    respond_to do |format|
      if @user.update(user_params)
        format.html { redirect_to @user, notice: 'User was successfully updated.' }
        format.json { render :show, status: :ok, location: @user }
      else
        format.html { render :edit }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /users/1
  # DELETE /users/1.json
  def destroy
    @user.destroy
    respond_to do |format|
      format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
      format.json { head :no_content }
    end
  end
  def check_registered_email
      registered_email = params[:registered_email]
      member =Member.find_by_email(registered_email)
      if !member.nil?
        if member.user_id.nil?
          render json: {:status => 'true'}
        else
          user = User.find_by_id(member.user_id)
          render json: {:status => 'false',:data => user}
        end
      else
        render json: {:status => 'false',:data => nil}
      end
  end 

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_user
      @user = User.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def user_params
      params.require(:user).permit(:name, :nrc, :email, :phone, :address,:is_active,:user_type) 
    end
end
