import requests
import pandas as pd
import io
import json

# URL for the Google Sheets data in TSV format
url = "https://docs.google.com/spreadsheets/d/e/2PACX-1vS_2ZCpuv-0LrjKO6z4VKod20yNVg_IyeFqSeqFxuIQpPyPLRXHgp_nuZigz2AT61QTjajU6fPTba_g/pub?gid=0&single=true&output=tsv"

try:
    # Download the data from the URL
    response = requests.get(url)
    response.raise_for_status()  # Raise HTTPError for bad responses (4xx or 5xx)

    # Read the content as a string
    tsv_content = response.text.encode('latin1').decode('utf-8')
    
    #print(tsv_content)
#
    ## Use pandas to read the TSV content into a DataFrame
    #df = pd.read_csv(io.StringIO(tsv_content), sep='\t')
#
    ## Print the DataFrame (or do something else with it)
    #print(df)

except requests.exceptions.RequestException as e:
    print(f"Error downloading the file: {e}")
except pd.errors.ParserError as e:
    print(f"Error parsing the TSV data: {e}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")
    

# Split rows by new line character (\n)
rows = tsv_content.split('\r\n')

# Initialize an empty list to store the split data
data = []

# Iterate over each row and split it into columns using \t as delimiter
for row in rows:
    if row:  # Check if row is not empty to avoid adding empty lists for blank lines.
        columns = row.split('\t')
        data.append(columns)

print(data)

print(json.dumps(data, indent=4))

# Define the path and content
file_path = '/usr/share/nginx/html/dados.js'
content = 'var dados = ' + json.dumps(data, indent=4)

# Open the file and write content
try:
    with open(file_path, 'w') as f:
        f.write(content)
    print(f"Content successfully written to {file_path}")
except PermissionError:
    print(f"Permission denied when trying to write to {file_path}.")
except Exception as e:
    print(f"An error occurred: {e}")
