import requests
import io
from importlib import resources


import pandas as pnd



def get_db(logger):
    
    
    logger.info("Downloading the database...")
    sheet_id = "1dXJBIFjCghrdvQtxEOYlVNWAQU4mK-nqLWyDQeUZqek"
    #sheet_id = "1dCVOOnpNg7rK3iZmTDz3wybW7YrUNoClnqezT9Q5bpc" # alternative
    url = f"https://docs.google.com/spreadsheets/d/{sheet_id}/export?format=xlsx"
    response = requests.get(url)  # download the requested file
    if response.status_code == 200:
        excel_data = io.BytesIO(response.content)   # load into memory
        exceldb = pnd.ExcelFile(excel_data)
    else:
        logger.error(f"Error during download. Please contact the developer.")
        return 1
    
    
    # check table presence
    sheet_names = exceldb.sheet_names
    for i in ['T', 'R', 'M', 'authors']: 
        if i not in sheet_names:
            logger.error(f"Sheet '{i}' is missing!")
            return 1
        
        
    # load the tables
    db = {}
    db['T'] = exceldb.parse('T')
    db['R'] = exceldb.parse('R')
    db['M'] = exceldb.parse('M')
    db['authors'] = exceldb.parse('authors')
    
    
    # check table headers
    headers = {}
    headers['T'] = ['rid', 'rstring', 'kr', 'gpr_manual', 'name', 'author', 'notes']
    headers['R'] = ['rid', 'rstring', 'kr', 'gpr_manual', 'name', 'author', 'notes']
    headers['M'] = ['pure_mid', 'formula', 'charge', 'kc', 'name', 'inchikey', 'author', 'notes']
    headers['authors'] = ['username', 'first_name', 'last_name', 'role', 'mail']
    for i in db.keys(): 
        if set(db[i].columns) != set(headers[i]):
            logger.error(f"Sheet '{i}' is missing the columns {set(headers[i]) - set(db[i].columns)}.")
            return 1
        
    return db



def get_expcon(logger):
    
    
    logger.info("Downloading the experimental constraints file...")
    sheet_id = "1qGbIIipHJgYQjk3M0xDWKvnTkeInPoTeH9unDQkZPwg"
    url = f"https://docs.google.com/spreadsheets/d/{sheet_id}/export?format=xlsx"
    response = requests.get(url)  # download the requested file
    if response.status_code == 200:
        excel_data = io.BytesIO(response.content)   # load into memory
        exceldb = pnd.ExcelFile(excel_data)
    else:
        logger.error(f"Error during download. Please contact the developer.")
        return 1
    
    
    # check table presence
    sheet_names = exceldb.sheet_names
    for i in ['media', 'PM1', 'PM2A', 'PM3B', 'PM4A', 'authors']: 
        if i not in sheet_names:
            logger.error(f"Sheet '{i}' is missing!")
            return 1
        
        
    # load the tables
    expcon = {}
    expcon['media'] = exceldb.parse('media')
    expcon['PM1'] = exceldb.parse('PM1')
    expcon['PM2A'] = exceldb.parse('PM2A')
    expcon['PM3B'] = exceldb.parse('PM3B')
    expcon['PM4A'] = exceldb.parse('PM4A')
    expcon['authors'] = exceldb.parse('authors')
    
    
    # assign substrates as index
    expcon['media'].index = expcon['media'].iloc[:, 1]
    # remove first 2 useless column (empty & substrates)
    expcon['media'] = expcon['media'].iloc[:, 2:]
    
    
    for sheet in ['PM1', 'PM2A', 'PM3B', 'PM4A']:
        # assign wells as index
        expcon[sheet].index = expcon[sheet].iloc[:, 2]
        # remove first 3 useless columns
        expcon[sheet] = expcon[sheet].iloc[:, 3:]
    

    return expcon



def load_minimal_media():
    
    with resources.path("gsrap.assets", f"exp_constraints.xlsx") as asset_path: 
        expcon = pnd.read_excel(asset_path, sheet_name=None)
        
        expcon['media'].index = expcon['media'].iloc[:, 1]
        # remove first 2 useless column (empty & substrates)
        expcon['media'] = expcon['media'].iloc[:, 2:]
        
        media = ','.join(list(expcon['media'].columns))
        
        return expcon, media




