# Importing QISKit
import math, sys
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister

# Import basic plotting tools
from qiskit.tools.visualization import plot_histogram

# Import methods to connect with remote backends
from qiskit import available_backends, execute, register, get_backend

# Import token to use remote backends
try:
    sys.path.append("../../") # go to parent dir
    import Qconfig
    qx_config = {
        "APItoken": Qconfig.APItoken,
        "url": Qconfig.config['url']}
except:
    qx_config = {
        "APItoken":"YOUR_TOKEN_HERE",
        "url":"https://quantumexperience.ng.bluemix.net/api"}
    
#to enable sleep
import time

#connect to remote API to be able to use remote simulators and real devices
register(qx_config['APItoken'], qx_config['url'])
print("Available backends:", available_backends())

def input_state(circ, q, n):
    """n-qubit input state for QFT that produces output 1."""
    for j in range(n):
        circ.h(q[j])
        circ.u1(math.pi/float(2**(j)), q[j]).inverse()

def qft(circ, q, n):
    """n-qubit QFT on q in circ."""
    for j in range(n):
        for k in range(j):
            circ.cu1(math.pi/float(2**(j-k)), q[j], q[k])
        circ.h(q[j])

q = QuantumRegister(3)
c = ClassicalRegister(3)
qft3 = QuantumCircuit(q, c)

input_state(qft3, q, 3)
qft(qft3, q, 3)
for i in range(3):
    qft3.measure(q[i], c[i])
print(qft3.qasm())

simulate = execute(qft3, backend="local_qasm_simulator", shots=1024).result()
simulate.get_counts()

backend = "ibmqx4"
shots = 1024

if get_backend(backend).status["available"] is True:
   
    job_exp = execute(qft3, backend=backend, shots=shots)
    
    lapse = 0
    interval = 10
    while not job_exp.done:
        print('Status @ {} seconds'.format(interval * lapse))
        print(job_exp.status)
        time.sleep(interval)
        lapse += 1
    print(job_exp.status)
    
    results = job_exp.result()
    plot_histogram(results.get_counts())

