from os import environ as env

from AvenirCommon.Database import GB_get_db_json
from AvenirCommon.Util import formatCountryFName
from SpectrumCommon.Const.GB import GBCountryListDBName, GBDatabaseVersion, GB_SPECT_MOD_DATA_CONN_ENV, \
    GB_NO_COSTING_MODE, GB_IHT_COSTING_MODE, GB_TB_COSTING_MODE, GB_LIST_COSTING_MODE
from SpectrumCommon.Const.PJ import GB_LCOnTag, GB_TBCostingOnTag, GB_IHTOnTag

def getCalcYear(data):
    return data['<projectionData>']['calcYear']

def getFinalYear(data):
    return data['<projectionData>']['finalYear']

getYearIdx = lambda year, firstYear: year - firstYear 

def getYear(t, firstYear):
    return t + firstYear

def get_country_details(countryID, subNatCode = 0):
    countries = GB_get_db_json(env[GB_SPECT_MOD_DATA_CONN_ENV], 'globals', formatCountryFName(GBCountryListDBName, GBDatabaseVersion))
    for country in countries:
        if ((country['ISO3_Alpha']==countryID)): # and (country['subNatCode']==subNatCode)):
            return country
        
def get_country_ISO3Alpha(countryISO3: int):
    countries = GB_get_db_json(env[GB_SPECT_MOD_DATA_CONN_ENV], 'globals', formatCountryFName(GBCountryListDBName, GBDatabaseVersion))
    for country in countries:
        if country['ISO3_Numeric'] == int(countryISO3):
            return country['ISO3_Alpha']
    return 'notFound'
        
def get_country_ISO3Numeric(countryISO3_Alpha: str):
    countries = GB_get_db_json(env[GB_SPECT_MOD_DATA_CONN_ENV], 'globals', formatCountryFName(GBCountryListDBName, GBDatabaseVersion))
    for country in countries:
        if country['ISO3_Alpha'] == countryISO3_Alpha:
            return country['ISO3_Numeric']
    return 'notFound'
        
def get_costing_mode(modvars: dict):
    costing_mode = GB_NO_COSTING_MODE

    assert (GB_IHTOnTag in modvars) and (GB_TBCostingOnTag in modvars) and (GB_LCOnTag in modvars), 'Costing mode tag(s) missing in MVs'

    if modvars[GB_IHTOnTag]:
        costing_mode = GB_IHT_COSTING_MODE

    elif modvars[GB_TBCostingOnTag]:
        costing_mode = GB_TB_COSTING_MODE

    elif modvars[GB_LCOnTag]:
        costing_mode = GB_LIST_COSTING_MODE

    return costing_mode