from os import environ
from .VWModvarDef import *
from .VWUtil import *
from SpectrumCommon.Const.CS import *
from SpectrumCommon.Const.VW.VWTags import *
from AvenirCommon.Database import GB_get_db_json, GB_file_exists
import datetime

def updateFname(DBName, countryID, Region):
    FName = DBName + '_' + latest_DB_Version[DBName]
    
    if DBName == RegionData: 
        FName += '/' + Region
    
    elif DBName in DBC_DB_Names: 
        FName += '/' + countryID
    
    return FName    

def downloadDatabase(connection, countryID, DBName, Region = ''):    
    FName = updateFname(DBName, countryID, Region) + '.JSON'
    
    if GB_file_exists(connection, 'list', FName):
        return GB_get_db_json(connection, 'list', FName)

def init_modvars(countryID, first_year, final_year, extra, projection):     
    connection = environ['AVENIR_SW_DEFAULT_DATA_CONNECTION']

    VWModvars = {}

    level       = extra['level']
    dataSource  = extra['source']

    source = dataSource.split(" ")[0]
    surveyYear = dataSource.split(" ")[1]

    SubnatData_DB = downloadDatabase(connection, countryID, SubnatData)
    SubnatData_DB = SubnatData_DB[level][surveyYear]

    CurrentYear = datetime.datetime.now().date().strftime("%Y")
    
    y = first_year
    t = 0
    if final_year < int(CurrentYear):
      YearToUse = final_year
    else:
      YearToUse = int(CurrentYear)
    while y < YearToUse:
      t += 1
      y += 1

    VWModvars = {
        VW_FirstYearTag                          : Simple_Value_Init(first_year),
        VW_TotalPopTag                           : VW_TotalPop_Init(projection, SubnatData_DB),
        VW_TFRTag                                : VW_TFR_Init(projection, SubnatData_DB, source),
        VW_CPRTag                                : VW_CPR_Init(projection, SubnatData_DB, source),
        VW_IncidenceTag                          : VW_Incidence_Init(projection),
        VW_PMTCTTag                              : VW_PMTCT_Init(projection, t),
        VW_CotrimTag                             : VW_Cotrim_Init(projection, t),
        VW_AdultARTTag                           : VW_AdultART_Init(projection, t)
    }
    
    return VWModvars