from __future__ import print_function
import pickle
import os.path
from typing import List, Dict

from googleapiclient.discovery import build, Resource
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']

# The ID and range of a sample spreadsheet.
SAMPLE_SPREADSHEET_ID = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms'
SAMPLE_RANGE_NAME = 'Haupt!A6:A42'

class GoogleSpreadSheetCrawler:

    def __init__(self):
        """Shows basic usage of the Sheets API.
                   Prints values from a sample spreadsheet.
                   """
        self.creds = None
        # The file token.pickle stores the user's access and refresh tokens, and is
        # created automatically when the authorization flow completes for the first
        # time.
        if os.path.exists('token.pickle'):
            with open('token.pickle', 'rb') as token:
                self.creds = pickle.load(token)
        # If there are no (valid) credentials available, let the user log in.
        if not self.creds or not self.creds.valid:
            if self.creds and self.creds.expired and self.creds.refresh_token:
                self.creds.refresh(Request())
            else:
                flow = InstalledAppFlow.from_client_secrets_file(
                    'credentials.json', SCOPES)
                self.creds = flow.run_local_server(port=0)
            # Save the credentials for the next run
            with open('token.pickle', 'wb') as token:
                pickle.dump(self.creds, token)

        service = build('sheets', 'v4', credentials=self.creds)

        # Call the Sheets API
        self.sheet = service.spreadsheets()

    def crawl_spreadsheet(self, sheet_id: str, range_descritpor: str):
        result = self.sheet.values().get(spreadsheetId=sheet_id,
                                    range=range_descritpor).execute()
        values = result.get('values', [])

        return values

    def post_data(self, sheet_id: str, range: str, values: List[List[str]]):
        body: Dict[str, any] = {"range": range, "majorDimension": "ROWS", "values": values}
        request = self.sheet.values().append(body=body, spreadsheetId=sheet_id, range=range, valueInputOption="RAW")
        request.execute()
