#!/usr/bin/env python2
"""Read from stdin and put data onto google spreadsheet.

usage: putsheet SPREADSHEET WORKSHEET AUTHFILE

Input data should be CSV, with the first row being the column names.
"""

import sys
import json

import gspread
from oauth2client.service_account import ServiceAccountCredentials

scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']

try:
    spreadsheet_name, worksheet_name, authfile = sys.argv[1:4]
except ValueError:
    sys.stderr.write("Not enough input arguments.\n")
    sys.exit(1)

with open(authfile, "r") as f:
    auth = json.load(f)

credentials = ServiceAccountCredentials.from_json_keyfile_name(authfile, scope)
spreadsheet = gspread.authorize(credentials).open(spreadsheet_name)
worksheet = spreadsheet.worksheet(worksheet_name)

table = [line.rstrip("\n").split(",") for line in sys.stdin]
nrows, ncols = len(table), len(table[0])
worksheet.resize(rows=nrows, cols=ncols)
endcell = gspread.utils.rowcol_to_a1(nrows, ncols)
cell_list = worksheet.range("A1:" + endcell)
table_list = [cell for row in table for cell in row]

for cell, cell_value in zip(cell_list, table_list):
    cell.value = cell_value
worksheet.update_cells(cell_list)
