import sys, time, getpass
try:
    sys.path.append("../../") # go to parent dir
    import Qconfig
    qx_config = {
        "APItoken": Qconfig.APItoken,
        "url": Qconfig.config['url']}
    print('Qconfig loaded from %s.' % Qconfig.__file__)
except:
    APItoken = getpass.getpass('Please input your token and hit enter: ')
    qx_config = {
        "APItoken": APItoken,
        "url":"https://quantumexperience.ng.bluemix.net/api"}
    print('Qconfig.py not found in qiskit-tutorial directory; Qconfig loaded using user input.')

from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, QISKitError
from qiskit import available_backends, execute, register, least_busy

# Create a Quantum Register called "q" with 3 qubits
qr = QuantumRegister(3)

# Create a Classical Register called "c" with 3 bits
cr = ClassicalRegister(3)

# Create a Quantum Circuit called involving "qr" and "cr"
circuit = QuantumCircuit(qr, cr)

# Not gate on qubit 0
circuit.x(qr[0])

# Not gate on qubit 1
circuit.x(qr[1])

# Barrier to seperator the input from the circuit
circuit.barrier(qr[0])
circuit.barrier(qr[1])
circuit.barrier(qr[2])

# Toffoli gate from qubit 0,1 to qubit 2
circuit.ccx(qr[0], qr[1], qr[2])

# CNOT (Controlled-NOT) gate from qubit 0 to qubit 1
circuit.cx(qr[0], qr[1])

# measure gate from qr to cr
circuit.measure(qr, cr)

# QASM from a program

QASM_source = circuit.qasm()

print(QASM_source)

from qiskit.tools.visualization import circuit_drawer
circuit_drawer(circuit)

backend = 'local_qasm_simulator' 

# Create a Quantum Program for execution 
job = execute(circuit, backend)

job.status

result = job.result()

result.get_counts(circuit)

register(qx_config['APItoken'], qx_config['url'])

large_enough_devices = available_backends(lambda x: x.configuration['n_qubits'] > 3 and not x.configuration['simulator'])
backend = least_busy(large_enough_devices)
print("the best backend is " + backend)

shots = 1024           # Number of shots to run the program (experiment); maximum is 8192 shots.
max_credits = 3          # Maximum number of credits to spend on executions. 

job_exp = execute(circuit, backend=backend, shots=shots, max_credits=max_credits)

lapse = 0
interval = 30
while not job_exp.done:
    print('Status @ {} seconds'.format(interval * lapse))
    print(job_exp.status)
    time.sleep(interval)
    lapse += 1
print(job_exp.status)

result_real = job_exp.result()

result_real.get_counts(circuit)

jobID = job_exp.id

print('JOB ID: {}'.format(jobID))        