# import Aer here, before calling qiskit_ionq_provider
from qiskit import Aer

from qiskit_ionq import IonQProvider 

# Call provider and set token value
provider = IonQProvider(token='My token')

provider.backends()

from qiskit import QuantumCircuit

# Create a bell state circuit.
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])

# Show the circuit:
qc.draw()

from qiskit.providers.jobstatus import JobStatus

# Get an IonQ simulator backend to run circuits on:
backend = provider.get_backend("ionq_simulator")

# Then run the circuit:
job = backend.run(qc, shots=1000)

# Save job_id
job_id_bell = job.job_id()

# Fetch the result:
result = job.result()

from qiskit.visualization import plot_histogram

plot_histogram(result.get_counts())

# Next get an IonQ hardware backend to run circuits on:
qpu_backend = provider.get_backend("ionq_qpu")

# Then run the circuit:
qpu_job_bell = qpu_backend.run(qc)

# Store job id
job_id_bell = qpu_job_bell.job_id()

# Check if job is done
if qpu_job_bell.status() is JobStatus.DONE:
    
    print("Job status is DONE")
    
    # Fetch the result:
    qpu_result_bell = qpu_job_bell.result()
   
else:
    print("Job status is ", qpu_job_bell.status() )

# If job is finished, plot and validate results:
plot_histogram(qpu_result_bell.get_counts())

# Retrieve a previously executed job:
old_job = backend.retrieve_job(job_id_bell)

# Then render the old job results:
old_result = old_job.result()
plot_histogram(old_result.get_counts())

n=4
qc_cat = QuantumCircuit(n, n)
qc_cat.h(0)
for i in range(1,n):
    qc_cat.cx(0, i)

qc_cat.measure(range(n), range(n))

# Show the circuit:
qc_cat.draw()

# Run the circuit on the simulator and plot the results
job_cat = backend.run(qc_cat)

# Save job id
job_id_cat = job_cat.job_id()

# Fetch the result:
result_cat = job_cat.result()

plot_histogram(result_cat.get_counts())

# Then run the circuit on the hardware:
qpu_job_cat = qpu_backend.run(qc_cat)

# Save job id
qpu_job_id_cat = qpu_job_cat.job_id()

# Check if job is done
if qpu_job_cat.status() is JobStatus.DONE:
    
    print("Job status is DONE")
    
    # Fetch the result:
    qpu_result_cat = qpu_job_cat.result()
   
else:
    print("Job status is ", qpu_job_cat.status() )

# If job is finished, plot and validate results:
plot_histogram(qpu_result_cat.get_counts())