"""
Helpers to connect and work with google drive spreadsheets
"""
import gspread
import json
from   oauth2client.client import SignedJwtAssertionCredentials


def connect_to_gspread(google_api_key_file):
    json_key = json.load(open(google_api_key_file))
    scope = ["https://spreadsheets.google.com/feeds"]

    # authenticate
    credentials = SignedJwtAssertionCredentials(json_key["client_email"],
                                                json_key["private_key"].encode("utf-8"),
                                                scope)
    return gspread.authorize(credentials)


def get_spreadsheet(api_key_file_path, doc_key):
    gc = connect_to_gspread(api_key_file_path)
    return gc.open_by_key(doc_key)


def get_worksheet(spreadsheet, worksheet_id):
    return spreadsheet.get_worksheet(worksheet_id)


def worksheet_to_dict(wks, header='', start_row=1):
    """ Transform a gspread worksheet into a pandas DataFrame.

    :param wks:
    :param header:
    :param start_row:
    :return:
    """
    all_rows = wks.get_all_values()
    if not header:
        header = all_rows[0]

    #print(list(zip(header, all_rows)))
    #[dict(zip(header, values)) for values in all_rows[1:]]
    return [dict(zip(header, values)) for values in all_rows[start_row:]]


def get_spread_url(spread_key):
    return 'https://docs.google.com/spreadsheets/d/{}'.format(spread_key)


def get_live_form_url(form_key):
    return 'https://docs.google.com/forms/d/{}/viewform'.format(form_key)


def get_edit_form_url(form_key):
    return 'https://docs.google.com/forms/d/{}/edit'.format(form_key)
