#!/usr/bin/env python
# coding:utf-8
import gspread
from gspread import Worksheet
from oauth2client.service_account import ServiceAccountCredentials

GoogleDrive = {
        "type": "service_account",
        "project_id": "quickstart-1616645350080",
        "private_key_id": "c27137e7a9bcb56debff4266d7f5e0b75d84e514",
        "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQClKVOarC1QskWD\nHxoS/S/Gah0oge71Fd4jDLOAU7cqOWY5/gPzHysBKCoA+Hrq/LE/SzzwFnqfoZTJ\n7RsokQB07iRyipjv6cm1tfZvguA95LVEAgAcpbsIYa/3gDeZ1QvP6ntTlUMCUdza\nP4l/hl3U9ZNqLAa3axKGxeJug6845BgG3fe1gF12ukyqHecUO9Ys5lUB5HsGv32c\nsIezTPFnNRmXyTSPTC4ufeU8tUhF6D+B5/jnSk+Lt7qjHzVBhyHnx7Aa1hYI2KoX\nn5Pp2hD8vaJR6FxMN1S3YP1DQnsjavU/p/wkG0cca/MkVjDc4Wst+00KDmDQb/sY\ndCBw/5RNAgMBAAECggEADFPC0TMTqMe9h3VdUViDZdhKt9jG2JUawNv0U9orvCOP\nnTl32wATCiGQzQS+y+YzZol7kWHkIiEBxXaEhekYsyGJJ+FvW8zDyOO9coI+sW/u\nFZbeokS+ang8FYmE3N75ZDnYnZrw5u3sQX/nh9SkET6JE64YjD0aI2QGq//5JpJF\nBOWFcmRq+oC4b2MmxjbYYfASz9SioyGPmDM9pnj0qAsooh8lbNYG2ot+SXUmQ5G7\n9jcAXAQA/qhboPEWWZr2bRSHum1s7Tnp0nuVR6gPQ48THCyp+ozyZ51ggg7a+KIY\nqWK59VdzZHKadrMqrANDkZyFk8g4WEYOFbcoroOEsQKBgQDOKIVig9m66BoD8l/u\nuEVnPLueOabKdsavwOcTRhIAOmXYiA0Tjntt2UgFMO+yi4LZujRnB0SHv/j6+UPV\nM6+AOdMUOThto9HhWB2CWg+F1U4eYD064GPllC3uiL/hNAy5OdNrtseR6tlQAG+f\nbARm1GqFk9vVHVyTlpWAULfPxQKBgQDNF3EwUkoPV0wALMKX6V4NjYQx6CsjbN7V\ndbBKBgt+OEEt/yE9L9dwuf2mN7YA37zZUFNfeZUnTNAH2EsmInI6wlewvUK7b9eZ\n3FmZcFHV4hlqE8A2vJwk0U42nJuC9dP5bTL8ZFst9qtRdFwlnrZ3rZXzVEtmBKVt\npIDLAZMy6QKBgQCUx/ejZmZ/FjyYNpZ3UPN9kv4QLakqmte/RWc+qKYbFgokX+OY\nBo8bcuEgJfYHE9omSdTBuiQCGFCWx8flmPyCfLjR8o2/yqeQiqgZR+fF/W/4ShpG\nYGSX7f3MFVLtM0QvdQUYynty2ltk+juUgT8X+xq5NkFDp4IFXXqddSOCxQKBgBa4\nLhXIR+QDK6wpSTVC6ORfdPGCYqT9/oFvFCRfHw7QdIf/51K75gXa1LqBGWxnXKhG\nObYt5dQAslrsHwcOcdEIjmZJ0QaqkRu+ST6yLp6e+WnC3lwx8KozdZKfLqsHSIAt\nFKTZCTDCTqArX7nbJyOC20WlZOTcRucqfgn/FqthAoGAe7aZTcUxLbtltXki9nym\nOWQ5WTbwSJukzG8BWtG6vuvJf+tyUvEcMXw5cnrem58FrDUqt1NAS+jso1d+aB9n\n+DulSAgaec/8kYcAnx2EnDQlXceB94FOsjfKD/j2T7ONteieGLYleliXVdhWu/ay\nTIljZsJu1Lnnq49cS0TLgIU=\n-----END PRIVATE KEY-----\n",
        "client_email": "google-sheet@quickstart-1616645350080.iam.gserviceaccount.com",
        "client_id": "105134275998904574352",
        "auth_uri": "https://accounts.google.com/o/oauth2/auth",
        "token_uri": "https://oauth2.googleapis.com/token",
        "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
        "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/google-sheet%40quickstart-1616645350080.iam.gserviceaccount.com"
    }

google_drive_auth_scope = [
    'https://www.googleapis.com/auth/drive',
    'https://www.googleapis.com/auth/drive.file'
]

def singleton(cls):
    _instance = {}

    def inner():
        if cls not in _instance:
            _instance[cls] = cls()
        return _instance[cls]
    return inner

@singleton
class GoogleSheetHelper:
    def __init__(self):
        cred = ServiceAccountCredentials.from_json_keyfile_dict(GoogleDrive, google_drive_auth_scope)
        self.googleDriveClient = gspread.authorize(cred)
        self.sheet_dict = {}

    def open_sheet_file(self, sheet_file_name):
        if sheet_file_name in self.sheet_dict:
            return self.sheet_dict[sheet_file_name]
        else:
            spread_sheet = self.googleDriveClient.open(sheet_file_name)
            self.sheet_dict[sheet_file_name] = spread_sheet
            return spread_sheet

    def get_sheet_table(self, sheet_file_name, sheet_table_name) -> Worksheet:
        try:
            spread_sheet = self.open_sheet_file(sheet_file_name)
            return spread_sheet.worksheet(sheet_table_name)
        except Exception as e:
            print(e)
            return None

    def get_or_create_sheet_table(self, sheet_file_name, sheet_table_name, row_count=1, col_count=1) -> Worksheet:
        spread_sheet = self.open_sheet_file(sheet_file_name)
        try:
            return spread_sheet.worksheet(sheet_table_name), False
        except:
            return spread_sheet.add_worksheet(sheet_table_name, row_count, col_count), True

    def get_sheet_row(self, sheet: Worksheet, row):
        if sheet is None:
            print('传入参数sheet异常 sheet is None')
            return
        if row < 0:
            print(f'传入参数row异常 row={row}')
            return
        return sheet.row_values(row)

    def sheet_append_row(self, sheet: Worksheet, value):
        if sheet is None:
            print('传入参数sheet is None')
            return
        sheet.append_row(value, value_input_option='USER_ENTERED')

    def sheet_update_cells_value(self, sheet: Worksheet, cell_range, values):
        if sheet is None:
            print('传入参数sheet is None')
            return
        for i, cell in enumerate(cell_range):
            cell.value = values[i]
        sheet.update_cells(cell_range)

    def sheet_update_cell_value(self, sheet: Worksheet, row, col, value):
        if sheet is None:
            print('传入参数sheet is None')
            return
        sheet.update_cell(row, col, value)

if __name__ == '__main__':
    sheet_helper = GoogleSheetHelper()
    # sheet: Worksheet = sheet_helper.get_sheet_table("find_object全关卡资源表", "iOS-AllLevels")
    # sheet: Worksheet = sheet_helper.get_sheet_table("find_object验收通过关卡资源表", "main")
    # sheet = sheet_helper.get_sheet_table("FindObject.Level.Config", "main资源表")
    # value_dict = sheet.get_all_values()
    # print(str(value_dict))