import time
import os
import numpy as np
from IPython.display import display

from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, transpile
from qiskit.visualization import plot_histogram, circuit_drawer

from quantuminspire.credentials import get_authentication
from quantuminspire.qiskit import QI

QI_URL = os.getenv('API_URL', 'https://api.quantum-inspire.com/')

def pcircuit(nqubits, depth = 10):
    """ Circuit to test performance of quantum computer """
    q = QuantumRegister(nqubits)
    ans = ClassicalRegister(nqubits)
    qc = QuantumCircuit(q, ans)

    for level in range(depth):
        for qidx in range(nqubits):
            qc.h( q[qidx] )
        qc.barrier()
        for qidx in range(nqubits):
            qc.rx(np.pi/2, q[qidx])
        qc.barrier()

        for qidx in range(nqubits):
            if qidx!=0:
                qc.cx(q[qidx], q[0])
    for qidx in range(nqubits):
        qc.measure(q[qidx], ans[qidx])
    return q, qc

q,qc = pcircuit(4, 1)
qc.draw(output='mpl')

authentication = get_authentication()
QI.set_authentication(authentication, QI_URL)

qi_backend = QI.get_backend('QX single-node simulator')
qc = transpile(qc, qi_backend)
job = qi_backend.run(qc)

result = job.result()
print('Generated histogram:')
print(result.get_counts())

plot_histogram(result.get_counts(qc))

q, qc = pcircuit(10, 10)
start_time = time.time()

qc = transpile(qc, qi_backend)
job = qi_backend.run(qc, shots=8)
job.result()
interval = time.time() - start_time

print('time needed: %.1f [s]' % (interval,))

