import gspread
import config
import datetime
import uuid
import httplib2

from oauth2client.file import Storage

def refresh_access_token():
    creds.refresh(httplib2.Http())
    storage.put(creds)

print "Loading DB..."

storage = Storage('credentials-nhshd.dat')
creds = storage.get()
refresh_access_token()
gs = gspread.authorize(creds)
sheet = gs.open_by_key(config.google_sheet_key)
log_worksheet = sheet.worksheet("log")
student_worksheet = sheet.worksheet("students")

print "Complete"


def to_timestamp(dt):
    return (dt - datetime.datetime(1970, 1, 1)).total_seconds()


def get_all_students():
    refresh_access_token()
    return student_worksheet.get_all_records()


def get_all_opportunities():
    refresh_access_token()
    rs = log_worksheet.get_all_records()


    for r in rs:
        if r["student"]:
            r["status"] = "Accepted"
        elif to_timestamp(datetime.datetime.now()) > int(r["expiry_time"]):
            r["status"] = "Expired"
        else:
            r["status"] = "Offered"

        r["time"] = datetime.datetime.fromtimestamp(r["time_sent"])
    return rs


## Call this function with a new opportunity:
# db.add_opportunity({
#        "doctor": "Dr Thing",
#        "procedure":"do thing",
#        "location": "the ward",
#        "duration": 20
#    })
#
# Returns the GUID of the created opportunity
def add_opportunity(op):
    refresh_access_token()

    vs = [uuid.uuid4()]

    now = to_timestamp(datetime.datetime.now())
    vs.append(op["doctor"])
    vs.append(now)
    vs.append(op["procedure"])
    vs.append(int(now + int(op["duration"]) * 60))
    vs.append(op["location"])
    log_worksheet.append_row(vs)

    return vs[0]

@@ -1684,8 +1684,321 @@
 n vs%5B0%5D%0A
+%0Adef update_opportunity(guid, student_name):%0A    refresh_access_token()%0A%0A    ops = get_all_opportunities()%0A%0A    i = 1%0A    x = None%0A    for op in ops:%0A        i+=1%0A        if op%5B%22id%22%5D == guid:%0A            x = op%0A            break%0A%0A    print %22Found op%22%0A    print x%0A%0A    log_worksheet.update_cell(i, 7, student_name)

Allow updating opportunities when they are taken.