import gspread # domentation: https://gspread.readthedocs.io/en/latest/index.html Storing data in a Google Sheet using Google Drive and Google Sheet APIs
from oauth2client.service_account import ServiceAccountCredentials
import pts_ligue_scrapping

"""
In order to use Google Sheets with Python
Step 1: Enable Google Sheets API and get Service Account credentials from Google API's Console
        By enabling Google Sheets API in Google Developpers Console, we can access the API and get data from Google Sheets.
Step 2: Import gspread and oauth2client modules
"""

# Determine the scope (access range)
scope = ["https://www.googleapis.com/auth/drive"] # Full, permissive scope to access all of a user's files. Request this scope only when it is strictly necessary.

# Since i'm editing spreadsheets on behalf of myself and not on behalf of an application for other users, I can use the Signed Credentials generated by Google Cloud Console which is stored in your application
credentials = ServiceAccountCredentials.from_json_keyfile_name(r"./Credentials/credentials.json", scope)

# Create a client object that interacts with Google Sheets API 
client = gspread.authorize(credentials)

# Creating a new SpreadSheet 
spreadsheet = client.create("FC Gatineau Schedule") # this new spreadsheet will be visible only to your script’s account (mlierjun@causal-bison-245613.iam.gserviceaccount.com), therefore we need to share it. This method need full access Google Drive scope

# Get first sheet
sheet1 = spreadsheet.sheet1              # Shortcut property for getting the first worksheet: .sheet1 will always refer to the first sheet of the Google Sheet document whatever the first sheet's actual name is. It is a special Worksheet attribute. We could use .worksheet("ThirdWorksheet") or .get_worksheet(1).
sheet1.update_title("Events")            # Renaming current sheet to "Events". 
sheet1.clear()                           # Each time it opens this worksheet, it clears all the values to write new ones

# Writing data
sheet1.append_row(pts_ligue_scrapping.headers)
for event in pts_ligue_scrapping.events:
    sheet1.append_row([event[0].strftime(r"%Y-%m-%dT%H:%M:%S"), event[1].strftime(r"%Y-%m-%dT%H:%M:%S"),event[2],event[3],event[4]])

# Sharing a Spreadsheet
spreadsheet.share("mlierjun@gmail.com", perm_type ="user", role="owner") # first argument: value (email) 2nd argument: perm_type (user=account type) 3rd argument: owner (owner, primary role for this user)

